← 返回完整题库
vue.js困难

说说 Vuex 的原理

参考答案

是什么

Vuex 是 Vue 2 时代的官方状态管理库,核心是单一状态树 + 严格的修改流程:

组件 → commit(mutation) → 修改 state → 响应式通知 → 组件更新
组件 → dispatch(action) → 异步 → commit(mutation)

原理拆解

  1. Store 构造:new Store(options),内部 this._state = reactive(state)(Vuex 4 用 reactive,Vuex 3 用 new Vue({data:{$$state}}) 借 Vue 响应式),对外暴露 get state();
  2. commit:this._withCommit(() => { entry.forEach(handler => handler(payload)) }),_withCommit 里把 this._committing = true,用于严格模式下检测「非 mutation 改 state」;
  3. 严格模式:store._vm.$watch(() => this._state, () => { if (!this._committing) assert(false) }, { deep: true, sync: true })——用深度 watcher 捕获「绕过 mutation」的修改并报错;
  4. dispatch:执行 action,action 里 commit;返回 Promise 以便链式;
  5. 模块化:modules 递归注册,生成 _modules/_children 树,namespaced: true 后把 getters/mutations/actions 加 moduleName/ 前缀,state 按层级挂到根 state 上;registerModule/unregisterModule 支持动态注册;
  6. 辅助函数:mapState/mapGetters/mapMutations/mapActions 生成 computed/methods,本质是 this.$store.state.xxx 的简写;
  7. 插件:store.subscribe((mutation, state) => {}) 订阅每次 commit(用于持久化、日志、devtools)。

为什么「只能 mutation 改」

为了可追踪与可调试:所有变更集中在一个同步入口,devtools 能记录快照与时间旅行;异步放进 action,保证 mutation 是同步的(否则快照不可靠)。

局限

样板代码多(一个状态三处声明)、TS 支持弱、模块命名空间繁琐、单一树导致模块耦合。这也是 Pinia 取代它的原因。

本题来自 计算机知识面试题库,共 921 道题。