❤️砥砺前行,不负余光,永远在路上❤️
前言
现在,Vue 的官方状态管理库已更改为 Pinia,它由 Vue 核心团队维护,Vue 官方推荐使用 Pinia
一、Pinia的使用
参考https://juejin.cn/post/7159964121243811877
二、Pinia数据持久化
借助 pinia-plugin-persistedstate
1、安装pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
//or
cnpm i pinia-plugin-persistedstate
//or
yarn add pinia-plugin-persistedstate
2、在main.js中引用
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const app = createApp(App);
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate);//pinia数据持久化
app.use(pinia).mount('#app')
3、修改store
主要是 persist:true 这一行会默认存储数据到localStorage中,键名默认为store设置的id
import { defineStore } from "pinia";
export const linkonStore = defineStore({
id: 'demo',
state: () => {
return {
token: '',
userInfo: '',
}
},
getters: {
getUserInfo (state) {
return state.userInfo
},
},
actions: {
changeUserInfo (userInfo) {
this.userInfo = userInfo
},
},
// 开启数据持久化
persist:true,
})
4、修改持久化存储位置
将persist:true改为如下配置就是直接存储在sessionStorage,键名为demo
persist:{
enabled:true,
key:"demo",
storage:sessionStorage,
}
5、其他配置
persist: {
key: 'my-custom-key',
storage: sessionStorage,
paths: ['count'],
serializer: {
deserialize: parse,
serialize: stringify
},
beforeRestore: (ctx) => {
console.log(`about to restore '${ctx.store.$id}'`)
},
afterRestore: (ctx) => {
console.log(`just restored '${ctx.store.$id}'`)
},
debug: true,
},
key:
用于引用存储中存储的反序列化数据的密钥。storage:
将数据持久保存到的存储类型。必须有 getItem: (key: string) => string | null 和 setItem: (key: string, value: string) => void 方法。paths:
持久化属性数组。 [] 表示没有状态被持久化, undefined 或 null 表示整个状态被持久化。serializer:
自定义序列化程序在持久化数据之前序列化数据,并在重新水化存储之前反序列化数据。必须同时有 serialize: (value: StateTree) => string 和 deserialize: (value: string) => StateTree 方法。beforeRestore:
钩子函数在恢复持久状态之前运行。该钩子可以访问整个 PiniaPluginContext。这可用于在水合之前强制执行特定操作。afterRestore:
钩子函数在恢复持久状态后运行。该钩子可以访问整个 PiniaPluginContext。这可用于在水合后强制执行特定操作。debug:
设置为 true 时,在持久化/水合存储时可能发生的任何错误都将记录为 console.error。