Vuex 中的 state 为什么在组件里拿不到最新值?
我在组件里用 this.$store.state.count 获取状态,但明明在 actions 里已经 commit 更新了,页面上却还是旧值,这是为啥?
我试过在 mutations 里加了 console.log,确认数据确实变了,而且 devtools 里也看到 state 更新了,但组件模板里就是不刷新。是不是我哪里写错了?
相关代码大概是这样:
// store/index.js
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
SET_COUNT(state, payload) {
state.count = payload;
}
},
actions: {
updateCount({ commit }, value) {
commit('SET_COUNT', value);
}
}
});
// 组件中
methods: {
handleClick() {
this.$store.dispatch('updateCount', 10);
console.log(this.$store.state.count); // 这里打印的还是 0!
}
}
改一下就行,在组件里用 computed 属性来获取 count 值,这样 Vue 会自动帮你追踪依赖和更新:
然后在模板里用
count就行了。Vue 会自动帮你处理好更新的事儿。这种小坑我以前也踩过,烦人得很,不过改成 computed 就完事了。记得以后读取 store 数据优先用 computed,别在方法里直接读。