data variable not being updated from watcher on computed property in Vue.js with Vuex

二次信任 提交于 2019-12-03 15:11:56

You missed the fact that ES6 arrow functions do not bind the this keyword (arrow functions aren't simply syntactic sugar over a regular function). So in your example, this inside the pets watcher defaults to window and myVar on the Vue instance is never set. If you change your code as follows, it works fine:

watch: {
    pets(pets) {
        console.log("Inside watcher")
        this.myVar = "Hey"
    }
}

That's because this is not what you expect in the inner function.

Try this:

watch:{
    var that = this;
    pets: (pets) => {
      console.log("Inside watcher")
      that.myVar = "Hey"
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!