数据变量未从观察者使用Vuex在Vue.js中的计算属性上更新

Sau*_*abh 5 javascript vue.js vuex vuejs2

小提琴:https : //jsfiddle.net/mjvu6bn7/

我对计算属性有一个监视程序,该属性对Vuex存储变量具有依赖性,该变量是异步设置的。当此计算属性更改时,我正在尝试设置Vue组件的数据变量,但这没有发生。

这是Vue组件:

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"
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

这是Vuex商店:

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
});
Run Code Online (Sandbox Code Playgroud)

是为此创建的小提琴。如您所见,myVar尚未更新,但是在加载宠物时会调用监视程序。

Ale*_*ios 4

您错过了 ES6 箭头函数不绑定this关键字的事实(箭头函数不仅仅是常规函数的语法糖function)。因此,在您的示例中,观察程序this内部pets默认为Vue 实例window,而myVarVue 实例上从未设置。如果您按如下方式更改代码,则它可以正常工作:

watch: {
    pets(pets) {
        console.log("Inside watcher")
        this.myVar = "Hey"
    }
}
Run Code Online (Sandbox Code Playgroud)