本文系统介绍大型 Nuxt 4 项目中 25 个 Pinia Store 的状态管理架构,深入分析 shallowRef 内存优化、localStorage 持久化白名单策略、路由级 KeepAlive 控制,以及配套的 memory profiling 工具链。大型 Nuxt 4 项目中 Pinia Store 的内存管理、持久化策略和路由级 KeepAlive 控制的完整方案一、项目 Store 体系概览
本项目使用 25 个独立的 Pinia Store,按职责分为四大类:
| 类别 | Store | 说明 |
|---|
| 内容类 | PostStore, ArchiveStore, SearchStore, DocumentStore, VideoStore | 文章/页面/归档/搜索/文档/视频 |
| 用户类 | LoginStore, UserCenterStore, AnswerStore, BookmarkStore, CommentStore | 登录/用户中心/问答/收藏/评论 |
| 业务类 | CartStore, ShopStore, ProductStore, OrderStore, PayStore | 购物车/商城/产品/订单/支付 |
| 系统类 | GeneralStore, HeaderStore, BuilderStore, EventStore | 通用配置/头部/构建器/事件 |
二、Pinia 持久化配置
// nuxt.config.ts
modules: [
['@pinia/nuxt', { autoImports: ['defineStore', 'storeToRefs', 'acceptHMRUpdate'] }],
'pinia-plugin-persistedstate/nuxt'
]
piniaPluginPersistedstate: {
cookieOptions: { sameSite: 'strict', secure: process.env.NODE_ENV !== 'development' },
storage: 'localStorage',
debug: process.env.NODE_ENV === 'development'
}
Store 级持久化
export const useCartStore = defineStore('cart', () => {
const items = ref([])
}, {
persist: { key: 'salong_cart', storage: localStorage, paths: ['items'] }
})
持久化白名单原则
| Store | 持久化字段 | 不持久化字段 | 理由 |
|---|
| CartStore | items | loading, error | 购物车需跨会话 |
| LoginStore | token, user | loading | 保持登录状态 |
| GeneralStore | options, theme | notifications | 用户偏好 |
| SearchStore | - | results, query | 无需持久化 |
三、shallowRef 内存优化
// ❌ ref 递归将整个对象树转换为响应式
const posts = ref<Post[]>([])
// ✅ shallowRef 只追踪数组引用变化
const posts = shallowRef<Post[]>([])
存储 100 篇文章(每篇约 5KB):
ref:递归追踪 ~500KB 数据 → ~2MB 额外内存
shallowRef:只追踪引用 → ~8KB 额外内存
四、路由级 KeepAlive
// middleware/keepalive.global.ts
const KEEPALIVE_MAX = 12
const keepaliveExcludeRules = [
/^\\/builder(?:\\/|$)/,
/^\\/login(?:\\/|$)/,
/^\\/cart(?:\\/|$)/,
/^\\/oauth(?:\\/|$)/,
// ...
]
export default defineNuxtRouteMiddleware((to) => {
if (shouldKeepAlive(to.path)) {
to.meta.keepalive = { max: KEEPALIVE_MAX }
}
})
| 路由 | KeepAlive | 理由 |
|---|
首页 / | ✅ 缓存 | 高频访问 |
内容详情 .html | ✅ 缓存 | 保持滚动位置 |
构建器 /builder | ❌ 不缓存 | 编辑态需实时 |
购物车 /cart | ❌ 不缓存 | 数据实时性 |
五、内存治理工具链
pnpm memory:test # 单元测试(缓存预算、请求韧性、页面活跃度)
pnpm memory:profile # --expose-gc 内存分析
pnpm memory:load # 压力测试
pnpm memory:analyze # 日志分析
六、总结
| 层级 | 机制 | 控制参数 |
|---|
| Store 级 | shallowRef 避免深层响应式 | 大数组/大对象用 shallowRef |
| 持久化级 | paths 白名单 + localStorage | 只持久化关键字段 |
| 路由级 | KeepAlive max=12 + 排除规则 | 高频页面缓存 |
| 缓存级 | LRU 预算控制 | 500 条 / 32MB 上限 |