标准答案
- option store 使用 state、getters、actions 选项,结构清楚,适合团队从 Vuex 迁移或业务状态比较标准的场景。
- setup store 像一个组合式函数,可以直接使用 ref、computed、watch 和其它 composable,适合复杂组合逻辑或需要复用组合式能力的场景。
- 两种写法都可以用。团队规范比个人偏好更重要,同一个项目里最好保持一致。
- 持久化适合保存 token、主题、语言、部分筛选条件、用户偏好这类刷新后仍有意义的状态。
- 不要持久化大列表、临时弹窗状态、过期服务端数据、权限明细和敏感信息。敏感 token 还要结合安全策略评估存储位置。
题目解析
setup store 的灵活性更高,但也更容易把 store 写成大杂烩。输入输出和状态边界要保持清楚。
持久化是缓存,不是数据库。服务端数据仍然需要过期策略和重新拉取。
权限类状态即使存在前端,也只能用于体验优化,不能作为真正授权依据。
代码示例
setup store 中可以直接使用 ref 和 computed,但仍然要保持清晰的返回边界。
TypeScript
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
export const usePreferenceStore = defineStore('preference', () => {
const theme = ref<'light' | 'dark'>('light')
const locale = ref('zh-CN')
const isDark = computed(() => theme.value === 'dark')
function setTheme(nextTheme: 'light' | 'dark') {
theme.value = nextTheme
}
return {
theme,
locale,
isDark,
setTheme
}
})常见误区
- 把 setup store 当成全局 composable,什么逻辑都往里塞。
- 把接口返回的大列表长期持久化,导致数据过期和本地存储膨胀。
- 把权限判断完全依赖持久化状态,忽略服务端校验和重新拉取。