数据变量没有从Vue.js中的监视器上的计算属性更新

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

本文关键字:监视器 计算 更新 属性 js 变量 Vue 数据      更新时间:2023-09-26

小提琴: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会被调用。

您忽略了ES6箭头函数不绑定this关键字的事实(箭头函数不只是普通function的语法糖)。因此,在您的示例中,pets监视程序中的this默认为window,而Vue实例上的myVar从未设置。如果按照下面的方式修改代码,就可以正常工作了:

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

这是因为这不是您期望的内部函数。

试试这个:

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