Vuex 中的 state 为什么在组件里拿不到最新值?

端木子硕 阅读 34

我在组件里用 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!
  }
}
我来解答 赞 4 收藏
二维码
手机扫码查看
1 条解答
好妍
好妍 Lv1
问题出在你直接读取 state 的时机不对。记住,Vuex 的更新是异步的,虽然你调用了 dispatch,但状态更新需要时间。当你马上读取 this.$store.state.count 时,还没来得及更新呢。

改一下就行,在组件里用 computed 属性来获取 count 值,这样 Vue 会自动帮你追踪依赖和更新:

export default {
computed: {
count() {
return this.$store.state.count;
}
},
methods: {
handleClick() {
this.$store.dispatch('updateCount', 10);
// 现在不用在这里读取 count 了
}
}
}


然后在模板里用 count 就行了。Vue 会自动帮你处理好更新的事儿。这种小坑我以前也踩过,烦人得很,不过改成 computed 就完事了。记得以后读取 store 数据优先用 computed,别在方法里直接读。
点赞
2026-03-26 22:03