前言

Pinia 是 Vue3 官方推荐的状态管理库,由 Vue 核心团队成员开发,定位上是 Vuex 5。它解决了 Vuex 的几个老问题:TS 支持差、mutations 写起来啰嗦、模块嵌套太深。在 Vite + Vue3 + TS 这套技术栈里,Pinia 是状态管理的默认选择。

本文延续前两篇的工程化骨架,把状态管理这一层讲透。

一、为什么不用 Vuex

Vuex 在 Vue2 时代是事实标准,但它在 Vue3 + TS 项目里有几个明显的痛点:

维度 Vuex 4 Pinia
TS 支持 类型推断弱,需手写 MutationTree 等 开箱即用,IDE 提示完整
Mutations 必须写 mutation 才能改 state 直接在 action 里改,或直接改
模块嵌套 modules 嵌套,访问要写 namespaced 路径 扁平 store,互相 import 即可
体积 较大 约 1KB(gzip)
Devtools 集成 集成且更直观
Composition API 需 useStore 包装 天然支持

简单说:Pinia = Vuex 减去 mutations 减去 modules 嵌套 + 完整 TS。

二、安装与初始化

1
2
3
pnpm add pinia
# 持久化插件(可选,但实战中常用)
pnpm add pinia-plugin-persistedstate

main.ts 注册

1
2
3
4
5
6
7
8
9
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

createApp(App).use(pinia).mount('#app')

三、defineStore 两种写法

Pinia 提供 Options Store 和 Setup Store 两种写法,本质等价,团队统一选一种即可。

Options Store(类 Vuex)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// src/stores/user.ts
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
state: () => ({
token: '' as string,
userInfo: null as UserInfo | null,
}),

getters: {
isLogin: (state) => !!state.token,
username: (state) => state.userInfo?.name ?? '游客',
},

actions: {
setToken(token: string) {
this.token = token
},
async login(form: LoginForm) {
const { token, userInfo } = await loginApi(form)
this.token = token
this.userInfo = userInfo
},
logout() {
this.token = ''
this.userInfo = null
},
},
})

Setup Store(Composition API 风格)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
// state
const token = ref('')
const userInfo = ref<UserInfo | null>(null)

// getters
const isLogin = computed(() => !!token.value)
const username = computed(() => userInfo.value?.name ?? '游客')

// actions
function setToken(t: string) {
token.value = t
}
async function login(form: LoginForm) {
const res = await loginApi(form)
token.value = res.token
userInfo.value = res.userInfo
}
function logout() {
token.value = ''
userInfo.value = null
}

return { token, userInfo, isLogin, username, setToken, login, logout }
})

怎么选

  • Options Store:结构清晰,从 Vuex 迁移过来成本低,团队新人上手快。
  • Setup Store:与 Composition API 一致,灵活,能在 store 里用 watch、provide 等。
  • 两者不要混用,按团队约定统一选一种。本文后续示例用 Setup Store。

四、在组件中使用 store

基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script setup lang="ts">
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 直接读
console.log(userStore.isLogin)

// 直接改 state
userStore.token = 'new-token'

// 调 action
userStore.logout()
</script>

<template>
<div>{{ userStore.username }}</div>
</template>

storeToRefs:解构不丢响应式

直接解构会丢响应式(和 reactive 一样的问题):

1
const { token, isLogin } = userStore  // ❌ 模板不会更新

用 storeToRefs 包一层:

1
2
3
4
5
import { storeToRefs } from 'pinia'

const { token, isLogin } = storeToRefs(userStore) // ✅ 保持响应式
// actions 是普通函数,直接解构没问题
const { login, logout } = userStore

五、getters 进阶

依赖其他 getter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const cart = defineStore('cart', () => {
const items = ref<CartItem[]>([])

const totalCount = computed(() =>
items.value.reduce((sum, i) => sum + i.count, 0),
)
const totalPrice = computed(() =>
items.value.reduce((sum, i) => sum + i.count * i.price, 0),
)
// 依赖其他 getter,直接 .value 引用
const avgPrice = computed(() =>
totalCount.value === 0 ? 0 : totalPrice.value / totalCount.value,
)

return { items, totalCount, totalPrice, avgPrice }
})

接收参数(用函数包一层)

如果 getter 需要外部参数,返回一个函数:

1
2
3
4
5
const findItem = computed(() => (id: number) =>
items.value.find((i) => i.id === id),
)

// 用法:cart.findItem(1)

注意:这种”getter 返回函数”每次取值都会重新创建函数,没有缓存效果,性能敏感场景慎用。

六、actions:业务逻辑的家

actions 是 Pinia 里发请求、改 state、抛错误的统一入口,相当于 Vuex 的 actions + mutations 合体。

异步 action

1
2
3
4
5
6
7
8
9
10
11
12
13
async function fetchList(params: ListParams) {
loading.value = true
try {
const res = await fetchListApi(params)
list.value = res.list
total.value = res.total
} catch (e) {
// 错误可以抛出,让调用方处理
throw e
} finally {
loading.value = false
}
}

组件里调用:

1
2
3
4
const cartStore = useCartStore()
await cartStore.fetchList({ page: 1 }).catch((e) => {
ElMessage.error(e.message)
})

$patch 批量更新

多个 state 一起改时用 $patch 性能更好(只触发一次渲染):

1
2
3
4
5
6
7
8
9
10
userStore.$patch({
token: 'xxx',
userInfo: { name: 'Tom' },
})

// 或函数式
userStore.$patch((state) => {
state.token = 'xxx'
state.userInfo = { name: 'Tom' }
})

$reset 重置

Options Store 自带 $reset,能重置到初始 state;Setup Store 需要自己实现:

1
2
3
4
function reset() {
token.value = ''
userInfo.value = null
}

七、跨 store 调用

Pinia store 是扁平的,互相之间直接 import + 实例化即可调用,不需要 Vuex 那种 namespaced 路径。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/stores/order.ts
import { defineStore } from 'vue'
import { useUserStore } from './user'

export const useOrderStore = defineStore('order', () => {
const orders = ref<Order[]>([])

async function createOrder() {
const userStore = useUserStore() // 在 action 里实例化
if (!userStore.isLogin) {
throw new Error('请先登录')
}
const res = await createOrderApi({ token: userStore.token })
orders.value.push(res)
}

return { orders, createOrder }
})

注意:不要在 store 顶层直接实例化别的 store,要在 action 内部实例化,避免循环依赖和初始化时机问题。

八、持久化:pinia-plugin-persistedstate

刷新页面后 state 默认丢失,登录态、主题色这些场景需要持久化。pinia-plugin-persistedstate 是社区方案里最稳的一个。

单个 store 开启持久化

1
2
3
4
5
6
7
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
state: () => ({ token: '', userInfo: null }),
// ...
persist: true, // 默认全部存到 localStorage,key 为 store id
})

自定义 key / storage / 选择性持久化

1
2
3
4
5
6
7
8
9
10
11
12
13
export const useUserStore = defineStore('user', {
state: () => ({
token: '',
userInfo: null,
tempData: '', // 不需要持久化的
}),
persist: {
key: 'my-app-user',
storage: sessionStorage,
pick: ['token', 'userInfo'], // 只持久化这两项
omit: ['tempData'], // 或排除某些项(二选一)
},
})

Setup Store 的持久化

1
2
3
4
5
6
7
8
9
10
11
export const useUserStore = defineStore('user', () => {
const token = ref('')
const userInfo = ref<UserInfo | null>(null)

return { token, userInfo }
}, {
persist: {
key: 'my-app-user',
pick: ['token'],
},
})

注意事项

  • 不要持久化大对象:列表数据放 store 又持久化会导致 localStorage 撑爆,仅持久化关键标识,进页面后再请求获取数据。
  • 敏感数据:token 这种放 localStorage 有 XSS 风险,生产环境考虑用 HttpOnly Cookie 或加密存储。
  • SSR 项目:storage 在服务端不存在,需要走 cookie 或自定义 storage 适配器。

九、模块化组织

Pinia 没有 Vuex 的 modules 概念,每个 defineStore 就是一个独立 store。建议按”业务域”拆分文件:

1
2
3
4
5
6
7
src/stores/
├── index.ts # 统一出口(可选)
├── user.ts # 用户域
├── cart.ts # 购物车域
├── order.ts # 订单域
├── app.ts # 全局 UI 状态(侧边栏折叠、主题)
└── permission.ts # 权限/动态路由

index.ts 统一导出:

1
2
3
4
export * from './user'
export * from './cart'
export * from './order'
export * from './app'

调用方:

1
import { useUserStore, useCartStore } from '@/stores'

十、Devtools 调试

Pinia 与 Vue Devtools 深度集成,能做的几件事:

  1. Time travel:回到任意一次 state 修改前的状态。
  2. 直接编辑 state:在 Devtools 里改值测试 UI。
  3. Action 追踪:看 action 执行的入参、返回、错误。
  4. Getter 实时值:getter 变化时实时显示。

排错流程:打开 Devtools → Pinia 面板 → 选定 store → 看 timeline 里最近几次变更,定位是哪个 action 改坏了 state。

十一、最佳实践速查

场景 建议
只在一个组件用的状态 不要进 store,放组件 ref/reactive 即可
多组件共享的”读多写少” 进 store + computed getter
跨页面共享的会话状态(登录、主题) store + 持久化
列表分页数据 进 store 但不持久化,进页面再请求
表单临时草稿 用 composable 抽取,不要进全局 store
跨 store 调用 action 内部实例化对方 store
大型对象 / 数组改一项 用 $patch 函数式更新,性能更好
store 太大 按业务域拆分,单个 store 别超过 200 行

十二、从 Vuex 迁移清单

Vuex 写法 Pinia 对应
state: () => ({}) state: () => ({}) 或 ref()
getters: { x: (state) => ... } getters: { x: (state) => ... } 或 computed()
mutations: { SET_X(state, v) { state.x = v } } 删除,直接改或写 action
actions: { async fetch() {} } actions: { async fetch() {} } 或函数
dispatch('user/login') useUserStore().login()
commit('user/SET_TOKEN', v) useUserStore().token = v
mapState / mapGetters storeToRefs(useXxxStore())
modules: { user: {...} } 拆成多个 defineStore('user') 文件

小结

Pinia 在 Vite + Vue3 + TS 这套技术栈里几乎是”零学习曲线就能写对”的状态管理库。掌握本文后你能:

  1. 选 Options Store 还是 Setup Store,并按团队约定统一。
  2. 用 storeToRefs 安全解构、用 $patch 批量更新、用 $reset 重置。
  3. 写带缓存的 getters 和返回函数的参数化 getter。
  4. 在 action 内部实例化对方 store,实现跨 store 调用。
  5. 用 pinia-plugin-persistedstate 做选择性持久化,避开大对象和敏感数据的坑。
  6. 按业务域拆分 store 文件,配合 Vue Devtools 高效排错。

下一篇是这套技术栈的最后一环——TypeScript 在 Vue3 里的类型进阶,把 props、emits、provide/inject、泛型组件的类型写法讲透,让类型真正成为开发期的”安全网”。