说说 Vuex 的原理
参考答案
是什么
Vuex 是 Vue 2 时代的官方状态管理库,核心是单一状态树 + 严格的修改流程:
组件 → commit(mutation) → 修改 state → 响应式通知 → 组件更新
组件 → dispatch(action) → 异步 → commit(mutation)
原理拆解
- Store 构造:
new Store(options),内部this._state = reactive(state)(Vuex 4 用reactive,Vuex 3 用new Vue({data:{$$state}})借 Vue 响应式),对外暴露get state(); - commit:
this._withCommit(() => { entry.forEach(handler => handler(payload)) }),_withCommit里把this._committing = true,用于严格模式下检测「非 mutation 改 state」; - 严格模式:
store._vm.$watch(() => this._state, () => { if (!this._committing) assert(false) }, { deep: true, sync: true })——用深度 watcher 捕获「绕过 mutation」的修改并报错; - dispatch:执行 action,action 里
commit;返回 Promise 以便链式; - 模块化:
modules递归注册,生成_modules/_children树,namespaced: true后把getters/mutations/actions加moduleName/前缀,state 按层级挂到根 state 上;registerModule/unregisterModule支持动态注册; - 辅助函数:
mapState/mapGetters/mapMutations/mapActions生成 computed/methods,本质是this.$store.state.xxx的简写; - 插件:
store.subscribe((mutation, state) => {})订阅每次 commit(用于持久化、日志、devtools)。
为什么「只能 mutation 改」
为了可追踪与可调试:所有变更集中在一个同步入口,devtools 能记录快照与时间旅行;异步放进 action,保证 mutation 是同步的(否则快照不可靠)。
局限
样板代码多(一个状态三处声明)、TS 支持弱、模块命名空间繁琐、单一树导致模块耦合。这也是 Pinia 取代它的原因。