Pinia 核心架构概述
Pinia 是 Vue 3 官方推荐的全局状态库,替代 Vuex 4。核心:无 mutations、扁平多 store、Vue 响应式原生、TypeScript 友好。
1. 与 Vuex 对比
| Vuex 4 | Pinia | |
|---|---|---|
| 变更 | commit mutation + dispatch action | 直接改 state 或 action 里改 |
| 结构 | 嵌套 modules + namespace | 多个独立 defineStore |
| TS | 类型需额外封装 | defineStore 推断 |
| 体积/心智 | 较重 | 更轻 |
2. 核心概念
| 概念 | 说明 |
|---|---|
| Pinia 实例 | createPinia() + app.use(pinia) |
| Store | defineStore(id, options | setup) |
| State | state: () => ({}),响应式 |
| Getters | 等同 computed |
| Actions | 可 async,可改 state |
| $patch / $subscribe | 批量更新、监听 |
3. 架构示意
mermaid
flowchart TB
App[Vue App] --> P[Pinia 实例]
P --> S1[useUserStore]
P --> S2[useCartStore]
S1 --> C1[组件 A]
S2 --> C2[组件 B]每个 store 以 id 注册在 pinia._s(Map)中;同 id 单例。
4. 两种定义 Store
| Options | Setup |
|---|---|
state / getters / actions | () => { ref; computed; function } |
| 迁移 Vuex 友好 | 组合式 API 友好 |
详见 02-Store实现机制。
5. 响应式
基于 Vue 3 reactive / ref;组件用 storeToRefs 解构保响应式。见 03。
6. 插件与 SSR
7. 总结
Pinia = Vue 官方态管理 + 去 mutations + 多 store 组合。读源码从 createPinia、createOptionsStore / setup store 入口即可。