@jiuyue-/pinia-persisted-state
v1.0.9
Published
Persisted state for Pinia
Readme
pinia-persisted-state
说明
pinia数据持久化
1. 安装
npm i @jiuyue-/pinia-persisted-state2. 引入 pinia-persisted-state
- 创建 pinia 并注册 pinia-persisted-state
// store/index.ts
import { createPinia } from 'pinia'
import createPersistedState from '@jiuyue-/pinia-persisted-state'
const pinia = createPinia()
// 1. 可以直接注册
// pinia.use(createPersistedState);
// 2. 也可以传入`PersistConfig`配置
pinia.use((context) =>
createPersistedState(context, {
// 存储数据的key
name: 'custom-pinia',
// 默认使用存储方式
storage: sessionStorage,
})
)
export default pinia- 在 main.ts 中注册 pinia
// main.ts
import { createApp } from 'vue'
import pinia from './store'
createApp(App).use(pinia).mount('#app')- 创建 store
- 在 store 中添加
persist属性,默认设置为true,表示开启本地持久化, 存储state中的所有数据。 - 也可以设置为一个
PersistOptions对象,结构如下:key属性表示存储的key,默认是store.$id。storage属性表示存储的storage,默认是localStorage, 可以设置为sessionStorage。paths属性表示需要持久化的state中的属性,如果不设置或者为空数组,则持久化state中的所有属性。
- 在 store 中添加
// store/counter.ts
import { defineStore } from 'pinia'
export const useCounter = defineStore({
id: 'counter',
state: () => ({
count: 0,
a: 3,
b: 4,
}),
// persist: true,
persist: {
key: 'counter',
storage: localStorage,
paths: ['count', 'a'],
},
})PersistConfig属性
type PersistConfig = {
name?: string
storage?: PersistStorage
}| 属性名称 | 属性描述 |
| -------- | ------------------------------------------------------------------------ |
| name | 存储数据的key, 默认是pinia |
| storage | 存储方式PersistStorage, 默认是localStorage, 可选项: sessionStorage |
PersistOptions属性
type PersistOptions = {
key?: string
storage?: PersistStorage
paths?: string[]
}| 属性名称 | 属性描述 |
| -------- | -------------------------------------- |
| key | 属性表示存储的key,默认是store.$id |
| storage | 属性表示存储的storage,默认是localStorage |
| paths | 属性表示需要持久化的state中的属性,如果不设置或者为空数组,则持久化state中的所有属性 |
