vue3 pinia 持久化存储

安装pinia

npm i pinia-plugin-persist --save

store/index.js

import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
store.use(piniaPluginPersist)
export default store

store/user.js【模块化】

export const useUserStore = defineStore({
  id: 'user',
  state: () => {
    return {
      name: '张三'
    }
  },  
  // 开启数据缓存
  persist: {
    enabled: true
  }
})

自定义 key

数据默认存在 sessionStorage 里,并且会以 store 的 id 作为 key

persist: {
  enabled: true,
    strategies: [
    {
      key: 'my_user',
      storage: localStorage,
    }
  ]
}

持久化局部 state

默认所有 state 都会进行缓存,你能够通过 paths 指定要长久化的字段,其余的则不会进行长久化。

state: () => {
  return {
    name: '张三',
    age: 18,
    gender: '男'
  }  
},

persist: {
  enabled: true,
  strategies: [
    {
      storage: localStorage,
      paths: ['name', 'age']
    }
  ]
}

猜你喜欢

转载自blog.csdn.net/irisMoon06/article/details/129023456