1.0.9 • Published 11 months ago

@jiuyue-/pinia-persisted-state v1.0.9

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

pinia-persisted-state

说明

pinia数据持久化

1. 安装

npm i @jiuyue-/pinia-persisted-state

2. 引入 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/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中的所有属性
1.0.9

11 months ago

1.0.8

11 months ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago