如何在 Pinia 中定义 state、getters 和 actions?它们的职责划分原则是什么?
解读
这道题在国内大厂一面中出现频率极高,面试官真正想考察的是:
- 你是否真的用过 Pinia,而不是只会背 API
- 你是否理解 Composition API 思维下的职责分层
- 你是否能把“可维护性”落到代码层面,而不是空谈规范
回答时务必给出“可运行、可扩展、可测试”的代码骨架,并指出与 Vuex 的差异,否则会被追问“为什么不用 Vuex”。
知识点
- 创建 Store 的三种语法:Options、Setup(Composition)、工厂函数
- state 必须返回函数,防止多实例共享引用
- getters 在 Setup 语法中就是 computed,天然缓存
- actions 支持异步,可直接修改 state,无需 commit
- 职责划分铁律:
- state → 纯数据,不含逻辑
- getters → 派生数据,无副作用,可组合
- actions → 一切副作用(接口、路由跳转、其他 Store 调用)
- 国内项目普遍要求 TypeScript,必须演示类型推导
- 单元测试角度:state/getters 可纯函数断言,actions 用 mock 外部依赖
答案
下面以“商品列表”业务为例,用 Setup 语法演示国内团队最推荐的写法,并附带单元测试思路。
// src/stores/product.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { fetchProducts, Product } from '@/api/product'
export const useProductStore = defineStore('product', () => {
/* ========== state ========== */
const list = ref<Product[]>([])
const loading = ref(false)
const error = ref('')
/* ========== getters ========== */
const count = computed(() => list.value.length)
// 国内常问:getters 能否传参?答:返回函数即可,但会失缓存
const findById = computed(() => (id: number) =>
list.value.find(p => p.id === id)
)
/* ========== actions ========== */
async function loadAll() {
loading.value = true
error.value = ''
try {
const data = await fetchProducts()
list.value = data
} catch (e: any) {
error.value = e.message || '网络错误'
} finally {
loading.value = false
}
}
function decreaseStock(id: number, delta = 1) {
const item = list.value.find(p => p.id === id)
if (item && item.stock >= delta) {
item.stock -= delta
}
}
// 暴露给模板
return {
list,
loading,
error,
count,
findById,
loadAll,
decreaseStock
}
})
职责划分一句话总结:
- state 只放“可被序列化的最小数据集”
- getters 只做“数据加工”,绝不调接口
- actions 是“唯一入口”,所有异步、多 Store 协同、路由跳转都收拢于此
单元测试示例(Vitest):
import { setActivePinia, createPinia } from 'pinia'
import { beforeEach, describe, it, expect, vi } from 'vitest'
import { useProductStore } from '@/stores/product'
import * as productApi from '@/api/product'
vi.mock('@/api/product')
beforeEach(() => {
setActivePinia(createPinia())
})
describe('product store', () => {
it('loadAll 成功时更新 list', async () => {
const mockList = [{ id: 1, name: 'iPhone', stock: 10 }]
vi.mocked(productApi.fetchProducts).mockResolvedValue(mockList)
const store = useProductStore()
await store.loadAll()
expect(store.list).toEqual(mockList)
expect(store.loading).toBe(false)
expect(store.error).toBe('')
})
})
拓展思考
- 如果商品数据需要跨模块共享,但部分字段仅在当前模块使用,可引入“共享 Store + 局部 Store”两层架构,避免全局状态膨胀
- 对于高频变更的字段(如库存),可结合
shallowRef或storeToRefs做精细更新,减少 Vue 响应式开销 - 国内微前端场景下,主应用与子应用可能同时引入 Pinia,需通过
createPinia()实例隔离,并在 qiankun 的unmount生命周期里调用pinia._s.clear()防止内存泄漏 - 面试加分项:主动提到“Pinia 插件机制”,用插件自动记录 actions 日志、上报错误,展示你对企业级运维的理解