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

試著忘記壹切 提交于 2019-12-09 13:04:48

问题


Fiddle: https://jsfiddle.net/mjvu6bn7/

I have a watcher on a computed property, which has a dependency on Vuex store variable, which is being set asynchronously. I am trying to set data variable of Vue component, when this computed property is changing, but this is not happening.

Here is Vue component:

new Vue({
  el: '#app',
  store,
  data : {
        myVar : ""

  },
  beforeMount() {
        this.$store.dispatch('FETCH_PETS', {
        }).then(() => {
                    console.log("fetched pets")
        })

  },
  computed:{
      pets(){
        return this.$store.state.pets
      }
    },
  watch:{
    pets: (pets) => {
      console.log("Inside watcher")
      this.myVar = "Hey"
    }
  }
});

Here is Vuex store:

const state = {
  pets: []
};

const mutations = {
  SET_PETS (state, response) {
        console.log("SET_PETS")
    state.pets = response;
  }
};

const actions = {
 FETCH_PETS: (state) => {
      setTimeout(function() { 
            state.commit('SET_PETS', ['t7m12qbvb/apple_9', '6pat9znxz/1448127928_kiwi'])
    }, 1000)
 }
}

const store = new Vuex.Store({
  state,
  mutations,
  actions
});

Here is fiddle created for this. As you can see, myVar is not being updated, however watcher gets called when pets get loaded.


回答1:


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"
    }
}



回答2:


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"
    }


来源:https://stackoverflow.com/questions/40546323/data-variable-not-being-updated-from-watcher-on-computed-property-in-vue-js-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!