-
文档地址:https://seb-l.github.io/pinia-plugin-persist/basic-usage.html
有时候需要把pinia中的数据持久化存储(存到localstorage或sessionstorage中)
pinia-plugin-persist插件可以帮我们轻松的做到:
插件安装:
npm i pinia --save
npm i pinia-plugin-persist --save
main.js中装载插件
import { createApp } from 'vue' import App from './App.vue' import { createPinia } from 'pinia' import piniaPersist from 'pinia-plugin-persist' const app = createApp(App); const pinia = createPinia(); pinia.use(piniaPersist); app.use(store) .use(pinia) .mount('#app')
存储策略
整个仓库存储
import { defineStore } from 'pinia' export const useUserStore = defineStore('storeUser', { state: () => { return { firstName: 'S', lastName: 'L', accessToken: 'xxxxxxxxxxxxx' } }, actions: { setToken (value: string) { this.accessToken = value } }, persist: { enabled: true , // 这个配置代表存储生效,而且是整个store都存储 } })
指定字段存储,并且指定存储方式:
// store/use-user-store.ts export const useUserStore = defineStore('storeUser', { state () { return { firstName: 'S', lastName: 'L', accessToken: 'xxxxxxxxxxxxx', } }, persist: { enabled: true, strategies: [ { storage: sessionStorage, paths: ['firstName', 'lastName'] }, // firstName 和 lastName字段用sessionStorage存储 { storage: localStorage, paths: ['accessToken'] }, // accessToken字段用 localstorage存储 ], }, })
-