Vuex 入门:状态管理与数据流
Vuex 入门:状态管理与数据流
当多个组件共享同一份数据(用户信息、购物车、全局通知),靠 props 和事件总线传递会变成蜘蛛网。Vuex 把共享状态抽到组件之外,集中管理。
核心概念
const store = new Vuex.Store({
state: { count: 0, user: null },
getters: { // 相当于 store 的计算属性
doubleCount: (state) => state.count * 2,
},
mutations: { // 改 state 的唯一方式:同步函数
increment(state, n) { state.count += n },
},
actions: { // 提交 mutation,可以包含异步
incrementAsync({ commit }, n) {
setTimeout(() => commit('increment', n), 1000)
},
},
})
严格的数据流
组件 dispatch → actions(可异步)→ commit → mutations(同步)→ state → 视图更新
为什么改 state 必须走 mutation?因为每一次修改都能被 devtools 追踪、回溯,直接改状态等于断了调试线索。开 strict: true,直接改 state 会直接报错。
组件里怎么用
this.$store.state.count // 读
this.$store.getters.doubleCount
this.$store.commit('increment', 2) // 同步改
this.$store.dispatch('incrementAsync', 2) // 异步改
大量状态映射可用辅助函数:mapState、mapGetters、mapActions。
模块化
state 多了按功能拆 modules:user、cart、post 各一个模块,支持命名空间 namespaced: true。
经验:不是所有数据都要进 Vuex——只放跨组件共享的状态;组件私有数据留在 data 里。Vue 3 项目推荐直接用 Pinia,API 更直观,对 TS 也更友好。
看到这里了?如果这篇文章帮到过你
请我喝瓶可乐就好 🥤

评论0 条
还没有评论,来抢沙发~