Reputation: 386
First, I have a Vue JS file --
export var myVue = new Vue({
el: '#myApp',
data: {
myCoordinates: new Set() // simple integers
},
methods: {
addCoordinates (c) {
this.myCoordinates.add(c);
}
}
}
Then I have a another JS file that imports the Vue and does some plotting --
import { myVue } from './my_vue.js';
myVue.addCoordinates(42);
myVue.$watch('myCoordinates', function(newVal, oldVal) {
console.log(newVal);
// plot the new coordinates
}, { deep: true });
The problem is the myVue.$watch
does not fire -- I can see myCoordinates
updated properly in Vue dev console, but myVue.$watch
just doesn't get trigggered. And I can't test watch as Vue's native as I can't move the plotting part into myVue
due to various restrictions.
The question is: What could have gone wrong in my case?
Edit: BTW, I'm using Webpack 4 to combine both JS files, would that have any side-effect?
Upvotes: 0
Views: 2153
Reputation: 386
It turns out that Vue2 watch does not support Set. See answers to my next question Vue2 watch Set Not Working
Upvotes: 1
Reputation: 2522
It's very likely that the watcher
has not been registered when you update your coordinates
as show in your code (it's registered after you call add
function). Similar to any kind of event listeners, you need to register the watcher / handler before the event happens for it to trigger.
With Vue
, you can always register the watcher functions when you create a new Vue instance, for example:
export var myVue = new Vue({
el: '#myApp',
data: {
myCoordinates: new Set() // simple integers
},
methods: {
addCoordinates (c) {
this.myCoordinates.add(c);
}
},
watch: {
myCoordinates: function(new, old) {
console.log(new, old);
}
}
}
Upvotes: 1