Pinia Plungin Persistedstate
入门指南 | Pinia 持久化状态插件 — Getting Started | Pinia Plugin Persistedstate
安装依赖
npm i pinia-plugin-persistedstate
添加插件(quasar项目stores/index.js)
import { defineStore } from '#q-app/wrappers'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
/** If not building with SSR mode, you can* directly export the Store instantiation;** The function below can be async too; either use* async/await or return a Promise which resolves* with the Store instance.*/export default defineStore((/* { ssrContext } */) => {const pinia = createPinia()// You can add Pinia plugins here// pinia.use(SomePiniaPlugin)pinia.use(piniaPluginPersistedstate)return pinia
})
启用持久化(stores/date-store.js)
import { defineStore, acceptHMRUpdate } from 'pinia'// 定义一个名为 'date' 的 Pinia 存储
export const useDateStore = defineStore('date', {state: () => ({ // 存储的初始状态dateStr: "2024-08-15 23:44"}),getters: { // 存储的计算属性(当前为空)}, actions: { // 存储的方法updateDate(newDateStr) { // 更新日期字符串的方法this.dateStr = newDateStr}},persist: true // 启用持久化(默认 localStorage)
})// 热模块替换(HMR)相关代码,用于开发环境
if (import.meta.hot) {import.meta.hot.accept(acceptHMRUpdate(useDateStore, import.meta.hot))
}
如果只需要基本功能,persist: true
已经足够了,它会:
- 使用 store 的 id (‘date’) 作为 localStorage 的 key
- 自动将 state 序列化为 JSON 存储
- 在 store 初始化时自动从 localStorage 恢复状态
如果需要更高级的配置,需要完整的配置对象,例如
persist: {enabled: true,strategies: [{key: 'date', // 存储的键名,默认是 store 的 idstorage: localStorage // 默认就是 localStorage}]
}
更多配置请见配置 | Pinia 持久化状态插件 — Configuration | Pinia Plugin Persistedstate