咨询热线:15911225507
龙霄
登录
首页-所有文章-Nuxt.js英文,Vue.js英文-正文

Pinia State Persistence & Memory Governance in Nuxt 4

龙霄龙霄
Nuxt.js英文, Vue.js英文
1个月前
0
0
4.76K
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 control

1. Store Architecture

25 independent Pinia Stores across four categories:

CategoryStoresPurpose
ContentPostStore, ArchiveStore, SearchStore, DocumentStore, VideoStoreArticles/archives/search/docs/video
UserLoginStore, UserCenterStore, BookmarkStore, CommentStoreAuth/profile/bookmarks/comments
BusinessCartStore, ShopStore, ProductStore, OrderStore, PayStoreCart/shop/products/orders/payments
SystemGeneralStore, HeaderStore, BuilderStore, EventStoreConfig/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 } }
})
RouteKeepAliveReason
/High-frequency
.html content pagesPreserve scroll position
/builderReal-time editing
/cartData 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

LayerMechanismControls
StoreshallowRefLarge arrays/objects
Persistencepaths whitelistKey fields only
RouteKeepAlive max=12High-frequency pages
CacheLRU budget500 entries / 32MB
标签:
本文原创,作者:龙霄,其版权均为龙霄所有。如需转载,请注明出处:https://lx.yfdxs.com/1426.html
龙霄

龙霄

Lv1Vip1Rec2
以 Nuxt.js 之力,焕新 WordPress 体验
137.56W1213.97W1W
加载中…
分享:
1
Nuxt 4 中 Naive UI 集成与 UnoCSS 原子化样式实战
Nuxt 4 中 Naive UI 集成与 UnoCSS 原子化样式实战上一篇
Nuxt 4 + WordPress GraphQL:数据管理策略与性能优化深度指南下一篇
Nuxt 4 + WordPress GraphQL:数据管理策略与性能优化深度指南
相关文章
总数:0
龙霄
没有相关内容
评论表单游客 您好,欢迎参与讨论。
加载中…
评论列表
总数:0
龙霄
没有相关内容