小提琴: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没有被更新,但是当宠物被加载时,观察者会被调用 .
2 回答
你错过了ES6箭头函数do not bind the this keyword的事实(箭头函数不仅仅是常规
function
的语法糖) . 因此,在您的示例中,pets
观察者内部的this
默认为window
,并且永远不会设置Vue实例上的myVar
. 如果您按如下方式更改代码,它可以正常工作:那是因为这不是你对内部函数的期望 .
试试这个: