pinia 数据持久化

·  阅读 304

插件地址:pinia-plugin-persistedstate

安装插件:

$ npm i  pinia-plugin-persistedstate
复制代码

main.ts中注册:

// storePinia/index.ts
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
export default pinia;

//main.ts
import { createApp } from 'vue'
import App from './App.vue'
import pinia from './storePinia'

createApp(App)
    .use(pinia)
    .mount('#app')
复制代码

模块开启持久化:

import { defineStore } from 'pinia'

export const useStore = defineStore('store', {
  state: () => {
    return {
      someState: 'hello pinia',
      someState2: {
        data1: 'pinia--1',
        data2: 'pinia--2',
      },
    }
  },
  persist: true,
})
复制代码

按需缓存某些模块的数据:

import { defineStore } from 'pinia'

export const useStore = defineStore('store', {
  state: () => {
    return {
      someState: 'hello pinia',
      someState2: {
        data1: 'pinia--1',
        data2: 'pinia--2',
      },
    }
  },
  
  // 模块所有数据持久化
  // persist: true,
  
  // 模块部分数据持久化
  persist: {
    key: 'someState2-data2', // 修改key名称
    storage: sessionStorage, //修改为 sessionStorage,默认为 localStorage
    paths: ['someState2.data2'],
  },
})
复制代码

分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改