简体   繁体   中英

Vue.js $watch Not Working

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?

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);
        }
    } 
}

It turns out that Vue2 watch does not support Set. See answers to my next question Vue2 watch Set Not Working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM