pinia 中数据可持续化
即:如何让 pinia 中的数据 状态 在刷新页面时候不丢失;
1、结合前端本地缓存 localStorage
,本地缓存方案自行脑补,不再赘述
2、引入插件使用
pinia-plugin-persistedstate 或者 pinia-plugin-persist;
建议使用 pinia-plugin-persistedstate
,因高级配置中更加灵活;
1、安装 pinia-plugin-persistedstate
yarn add pinia-plugin-persistedstate
2、main.ts 中引入使用
...
const app = createApp(App)
const pinia = createPinia()
//导入pinia 持久化 插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
// 使用可持续化插件
pinia.use(piniaPluginPersistedstate)
app.use(pinia)
...
3、在pinia的 store中使用
<script lang='ts'>
import { defineStore } from 'pinia'
export const useCount = defineStore('count', {
state: () => {return{name: 'Andy'}},
actions: {},
getters: {},
// persist: true // 不需要额外的可持续化配置;
// 额外配置
persist: {
// key: 'piniaStore', //存储名称
// storage: sessionStorage, // 存储方式 默认存储在localStorage
// paths: ['name'], //指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态,undefined 或 null 表示持久化整个 state
}
}
</script>
4、pinia-plugin-persistedstate 插件
默认情况下是:
A、使用 localStorage进行存储
B、store.$id
作为 storage
默认的 key
C、使用 JSON.stringify / JSON.parse
进行序列化/反序列化
D、整个 state 默认将被持久化
;
若需要额外修改配置内容 需要
A、key
:存储名称。
B、storage
:存储方式。
C、paths
:用于指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态
,undefined 或 null 表示持久化整个 state。
// count.ts 文件
import { defineStore } from 'pinia'
export const useCount = defineStore('count', {
state: () => {
return{
name: 'Andy',
num: 0
}
},
actions: {
add() {
this.num++
},
},
// getter 只会依赖状态
getters: {
// 相当于组件中的 计算属性
doubleCount(state): number {
return state.num * 2
},
doubleCountAdd():number {
// 可以在其他 getter 中直接调用另一个getter
return this.doubleCount + 1
},
// 接收额外参数,返回一个函数处理
doubleCountAdd2:(state) => {
return (num:number):number => state.num * num
}
},
// 若不需要额外配置,
// persist: true,
// 额外配置
persist: {
// key: 'piniaStore', //存储名称
// storage: sessionStorage, // 存储方式 默认存储在localStorage
// paths: ['name'], //指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态,undefined 或 null 表示持久化整个 state
}
})
如图:默认存储将键名为 count
的对象 存储在 localStorage
中