响应式系统与状态管理
Pinia 站在 Vue 3 reactivity 之上:state 经 reactive/ref 包装,组件 storeToRefs 解构保持响应式,更新走 Vue 依赖收集而非手动 subscribe。
1. 与 Vuex 差异
| Vuex | Pinia |
|---|---|
| Mutations 同步提交 | 无 mutations,直接改 state 或 $patch |
| 嵌套 modules | 扁平多 store |
| 严格模式 commit | 一般靠 ESLint / 约定 |
2. 更新路径
| API | 场景 |
|---|---|
store.count++ / 赋值 | 单字段 |
$patch({ a: 1 }) | 批量、DevTools 友好 |
$patch(s => { s.items.push(x) }) | 复杂逻辑仍一次通知 |
action 内改 this | Options store;Setup 内改 ref |
3. storeToRefs
解构 const { count } = store 会丢响应式;storeToRefs(store) 把 state/getters 转为 ref,actions 仍从 store 取。
4. $subscribe
- 监听 state 变化(可
detached在组件卸载后仍监听)。 - 与
watch(store, …)类似;适合持久化插件。
5. EffectScope
每个 store 绑定 EffectScope:销毁 store 时清理 computed、watch,避免泄漏(见 08 §5)。
6. 性能
- 组件只访问用到的字段 → 细粒度依赖(Vue 自动)。
- 大列表考虑 shallowRef、分 store。
- 避免在 getter 里做重计算无缓存 → 用
computed或 memo。
7. 总结
Pinia = Vue 响应式 + 命名 store;理解 reactive/storeToRefs/$patch 即理解 80% 行为。