I'm facing a challenge in updating the Vue component property, station
, whenever certain other properties are updated. Since computed properties are synchronous and this task involves an API request, I couldn't make it work as a computed property.
After reading an insightful response on Vue core issues, I came across the documentation for using vm.$watch
. It seems like this is what I need, but I'm struggling to implement it correctly within the context of this component.
I believe I should be using this
instead of vm
as mentioned in the docs, but when I try using this
on the left side of the arrow function that serves as the first parameter of $watch
, I encounter errors like
Invalid left-hand side in arrow function parameters
.
The section where I use vm.$watch
can be found towards the end of the code snippet for this component. The recurring error that I'm getting is:
Failed watching path: "[object Object]" Watcher only accepts simple dot-delimited paths. For full control, use a function instead.
(But isn't that what I'm doing...?)
<template lang="html">
<div>
{{ station }}
</div>
</template>
<script>
import ApiService from '@/services/ApiService';
export default {
name: 'Chart',
props: {
mode: String,
toDate: String,
toTime: String
},
data() {
return {
stationId: 3069,
station: {}
};
},
watch: {
station: function() {
// Render function
}
},
methods: {
getInfo: async function(opts) {
const stationData = await ApiService[this.mode]({
id: opts.id,
toTime: `${opts.toDate}T${opts.toTime}`,
fromTime: `${opts.fromDate}T${opts.fromTime}`
})
.then(res => {
return res.data.station.properties;
})
.catch(err => {
console.error(err);
return {};
});
return stationData;
}
},
created: function() {
// MY WATCHING STARTS HERE
this.$watch(
() => return {
mode: this.mode,
stationId: this.stationId,
toDate: this.toDate,
toTime: this.toTime
},
async function(data) {
this.station = await this.getInfo({
mode: data.mode,
id: data.stationId,
toDate: data.toDate,
toTime: data.toTime
}).then(res => {
return res;
});
}
);
}
};
</script>