【问题标题】:data variable not being updated from watcher on computed property in Vue.js with Vuex使用 Vuex 在 Vue.js 中的计算属性上未从观察者更新数据变量
【发布时间】:2017-03-25 14:04:15
【问题描述】:

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

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

【问题讨论】:

    标签: javascript vuex vue.js vuejs2


    【解决方案1】:

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

    试试这个:

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

    【讨论】:

    • 这实际上是一个语法错误 - 你不能将变量声明放在对象文字中。
    【解决方案2】:

    您错过了 ES6 箭头函数 do not bind the this keyword 的事实(箭头函数不仅仅是常规 function 的语法糖)。因此,在您的示例中,pets 观察程序中的 this 默认为 window 和 Vue 实例上的 myVar 永远不会设置。如果您按以下方式更改代码,则可以正常工作:

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

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 2017-09-16
      • 1970-01-01
      • 2016-04-22
      • 2020-08-11
      • 2023-04-08
      • 2021-11-08
      • 2017-07-29
      • 2023-01-24
      相关资源
      最近更新 更多