简体   繁体   English

Vue.js $ watch无法正常工作

[英]Vue.js $watch Not Working

First, I have a Vue JS file -- 首先,我有一个Vue JS文件-

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 -- 然后,我还有另一个JS文件,可以导入Vue并进行一些绘图-

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. 问题是myVue.$watch无法启动-我可以看到myCoordinates在Vue开发人员控制台中已正确更新,但是myVue.$watch只是没有触发。 And I can't test watch as Vue's native as I can't move the plotting part into myVue due to various restrictions. 而且由于各种限制,我无法将绘图部件移入myVue因此我无法测试Vue的原生功能。

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? 编辑:顺便说一句,我正在使用Webpack 4合并两个JS文件,这会有副作用吗?

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). 当您更新代码中显示的coordinates时,很可能尚未注册watcher (在调用add函数之后已注册watcher )。 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: 使用Vue ,您始终可以在创建新的Vue实例时注册观察器功能,例如:

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. 事实证明,Vue2手表不支持Set。 See answers to my next question Vue2 watch Set Not Working 查看我的下一个问题的答案Vue2手表设置不工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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