Pinia实现数据持久化存储

一.安装pinia-plugin-persist

npm i pinia-plugin-persist --save

二.store/index.ts中引入并挂载

import { createPinia, defineStore } from "pinia";
import piniaPluginPersist from 'pinia-plugin-persist'

const store = createPinia()
store.use(piniaPluginPersist)

export default store

三.使用方法

enabled: true即表示开启数据缓存

export const useUserStore = defineStore({id: 'userId',
  state: () => {
    return {
      userInfo:{
        name:'Ghmin',
        age:18,
        sex:'男'
        },
      id:'666666'
    }
  },
  // 开启数据缓存
  persist: {
    enabled: true
  }
})

这个时候数据默认是存在sessionStorage 里,需要修改的话如下:

persist: {
  enabled: true,
  strategies: [
    {
      key: 'userInfo',//设置存储的key
      storage: localStorage,//表示存储在localStorage
    }
  ]
}

默认所有 state 都会进行缓存,如果你不想所有的数据都持久化存储,那么可以通过 paths 指定要长久化的字段,其余的字段则不会进行长久化,如下:

persist: {
  enabled: true,
  strategies: [
    {
      storage: localStorage,
      paths: ['id'],//指定要长久化的字段
    }
  ]
}

猜你喜欢

转载自blog.csdn.net/G_ing/article/details/128242848
今日推荐