A systematic walkthrough of state management across 25 Pinia Stores in a large Nuxt 4 project, covering shallowRef memory optimization, localStorage persistence whitelisting, route-level KeepAlive control, and a comprehensive memory profiling toolchain.Complete guide to Pinia Store memory management, persistence strategies, and route-level KeepAlive control1. Store Architecture
25 independent Pinia Stores across four categories:
| Category | Stores | Purpose |
|---|
| Content | PostStore, ArchiveStore, SearchStore, DocumentStore, VideoStore | Articles/archives/search/docs/video |
| User | LoginStore, UserCenterStore, BookmarkStore, CommentStore | Auth/profile/bookmarks/comments |
| Business | CartStore, ShopStore, ProductStore, OrderStore, PayStore | Cart/shop/products/orders/payments |
| System | GeneralStore, HeaderStore, BuilderStore, EventStore | Config/header/builder/events |
2. Pinia Persistence
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'] }
})
3. shallowRef Memory Optimization
// ❌ ref deeply wraps entire object tree
const posts = ref<Post[]>([])
// ✅ shallowRef only tracks reference changes
const posts = shallowRef<Post[]>([])
With 100 articles (~500KB): ref adds ~2MB overhead, shallowRef adds ~8KB — 250x less.
4. Route-Level KeepAlive
const KEEPALIVE_MAX = 12
const keepaliveExcludeRules = [/^\\/builder/, /^\\/login/, /^\\/cart/, ...]
export default defineNuxtRouteMiddleware((to) => {
if (shouldKeepAlive(to.path)) { to.meta.keepalive = { max: KEEPALIVE_MAX } }
})
| Route | KeepAlive | Reason |
|---|
/ | ✅ | High-frequency |
.html content pages | ✅ | Preserve scroll position |
/builder | ❌ | Real-time editing |
/cart | ❌ | Data freshness |
5. Memory Governance Toolchain
pnpm memory:test # Unit tests
pnpm memory:profile # Memory profiling (--expose-gc)
pnpm memory:load # Load testing
pnpm memory:analyze # Log analysis
6. Summary
| Layer | Mechanism | Controls |
|---|
| Store | shallowRef | Large arrays/objects |
| Persistence | paths whitelist | Key fields only |
| Route | KeepAlive max=12 | High-frequency pages |
| Cache | LRU budget | 500 entries / 32MB |
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙
萨龙龙