5

小提琴: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"
    }
  }
});

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

是为此创建的小提琴。如您所见,myVar 没有更新,但是当宠物加载时会调用 watcher。

4

2 回答 2

4

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

watch: {
    pets(pets) {
        console.log("Inside watcher")
        this.myVar = "Hey"
    }
}
于 2016-11-11T23:16:35.803 回答
1

那是因为这不是您在内部函数中所期望的。

尝试这个:

watch:{
    var that = this;
    pets: (pets) => {
      console.log("Inside watcher")
      that.myVar = "Hey"
    }
于 2016-11-11T13:48:42.990 回答