Pinia implements persistent data storage

1. Install pinia-plugin-persist

npm i pinia-plugin-persist --save

2. Introduce and mount in store/index.ts

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

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

export default store

3. How to use

enabled: true means to enable data caching

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

At this time, the data is stored in sessionStorage by default. If you need to modify it, it is as follows:

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

By default, all states will be cached. If you don’t want all data to be persisted, you can specify the fields to be persisted through paths, and the rest of the fields will not be persisted, as follows:

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

Guess you like

Origin blog.csdn.net/G_ing/article/details/128242848