gpt4 book ai didi

javascript - 使用 Vuex 的 Vue.js 中的计算属性上的观察者未更新数据变量

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:01 25 4
gpt4 key购买 nike

fiddle :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是为此创建的 fiddle 。如您所见,myVar 没有更新,但是当宠物加载时会调用 watcher。

最佳答案

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

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

关于javascript - 使用 Vuex 的 Vue.js 中的计算属性上的观察者未更新数据变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40546323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com