pinia持久化存储插件pinia-plugin-persist

-

文档地址: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存储
    ],
  },
})
复制代码

 

 

 

-

posted @   古墩古墩  Views(8732)  Comments(1Edit  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2019-07-24 electron-vue搭建项目
点击右上角即可分享
微信分享提示