本文系統介紹大型 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 持久化
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'
}
export const useCartStore = defineStore('cart', () => {
const items = ref([])
}, {
persist: { key: 'salong_cart', storage: localStorage, paths: ['items'] }
})
三、shallowRef 記憶體最佳化
// ❌ ref 遞迴將整個物件樹轉換為響應式
const posts = ref<Post[]>([])
// ✅ shallowRef 只追蹤陣列引用變化
const posts = shallowRef<Post[]>([])
儲存 100 篇文章時:ref 約 2MB 額外記憶體,shallowRef 約 8KB。
四、KeepAlive
const KEEPALIVE_MAX = 12
const keepaliveExcludeRules = [/^\\/builder/, /^\\/login/, /^\\/cart/, ...]
export default defineNuxtRouteMiddleware((to) => {
if (shouldKeepAlive(to.path)) { to.meta.keepalive = { max: KEEPALIVE_MAX } }
})
| 路由 | KeepAlive | 理由 |
|---|
首頁 / | ✅ 快取 | 高頻訪問 |
內容詳情 .html | ✅ 快取 | 保持捲動位置 |
建構器 /builder | ❌ 不快取 | 編輯態需即時狀態 |
五、工具鏈
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 |