小提琴: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。