【pinia持久化存储】使用pinia和pinia-plugin-persistedstate依赖进行数据的持久化存储

简言

使用pinia和pinia-plugin-persistedstate依赖进行数据的持久化存储。
存储方式 :

  • localStorage
  • sessionStorage

pinia-plugin-persistedstate 中文官网

pinia 中文官网

安装

安装和使用 pinia ,请参考使用pinia文章。

安装 pinia-plugin-persistedstate :

npm i pinia-plugin-persistedstate
# 或
pnpm i pinia-plugin-persistedstate
# 或
yarn add pinia-plugin-persistedstate

使用pinia-plugin-persistedstate持久化存储

挂载

使用前先将 pinia-plugin-persistedstate添加到pinia实例上。

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

在添加的时候,可以添加参数修改pinia-plugin-persistedstate的 默认配置,例如:

pinia.use(piniaPluginPersistedstate({
	auto:true,	//	该配置将会使所有 Store 持久化存储,且必须配置 persist: false 显式禁用持久化。
    storage: sessionStorage,	//	默认持久化存储方式 修改为 sessionStorage
  })

上面的修改的默认配置是 开启所有的store持久化存储,且默认存储方式是sessionStorage

store上使用

创建 Store 时,将 persistent 选项设置为 true。

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  state: () => {
    return {
      someState: '你好 pinia',
    }
  },
  persist: true,
})

或者

import { defineStore } from 'pinia'

export const useStore = defineStore(
  'main',
  () => {
    const someState = ref('你好 pinia')
    return { someState }
  },
  {
    persist: true,
  }
)

上面的store内所有的数据都会开启持久化存储,使用默认配置。

默认配置

  • 使用 localStorage 进行存储
  • store.$id 作为 storage 默认的 key
  • 使用 JSON.stringify/JSON.parse 进行序列化/反序列化
  • 整个 state 默认将被持久化

个性化配置

persist可以是一个对象。

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  state: () => ({
    someState: '你好 pinia',
  }),
  persist: {
    // 在这里进行自定义配置
  },
})

persist对象可以配置以下属性:

  • key
    类型:string
    默认值:store.$id
    Key 用于引用 storage 中的数据
  • storage
    类型:StorageLike
    默认值:localStorage
    将数据持久化到的 storage 中,必须具有 getItem: (key: string) => string | null 和 setItem: (key: string, value: string) => void 两个方法
  • paths
    类型:string[]
    默认值:undefined
    用于指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态,undefined 或 null 表示持久化整个 state
  • serializer
    类型:Serializer
    默认值:JSON.stringify/JSON.parse
    该配置能够指定持久化时所使用的序列化方法,以及恢复 Store 时的反序列化方法。另外,必须具有 serialize: (value: StateTree) => string 和 deserialize: (value: string) => StateTree 方法。
  • beforeRestore
    类型:(context: PiniaPluginContext) => void
    默认值:undefined
    该 hook 将在从 storage 中恢复数据之前触发,并且它可以访问整个 PiniaPluginContext,这可用于在恢复数据之前强制地执行特定的操作。
  • afterRestore
    类型:(context: PiniaPluginContext) => void
    默认值:undefined
    该 hook 将在从 storage 中恢复数据之后触发,并且它可以访问整个 PiniaPluginContext,这可用于在恢复数据之后强制地执行特定的操作
  • debug
    类型:boolean
    默认值:false
    当设置为 true 时,持久化/恢复 Store 时可能发生的任何错误都将使用 console.error 输出

例子

/*
 * @Date: 2022-11-30 17:26:39
 * @LastEditors: zhangsk
 * @LastEditTime: 2023-04-14 11:26:46
 * @FilePath: \basic-demo\src\store\index.ts
 * @Label: Do not edit
 */
import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  //  类似data
  state: () => {
    return {
      userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo') as string) : undefined,
      token: undefined as string | undefined,
      num: 1,
    }
  },
  //  类似计算属性
  getters: {
    getNum2: (state) => state.num * 2
  },
  // 类似methods
  actions: {
    setUserInfo(info = null) {
      this.userInfo = info || undefined
      console.log(info);

      localStorage.setItem('userInfo', JSON.stringify(info))
    }
  },
  persist: {
    paths: ['num'],
    storage: sessionStorage,
    key: 'my_num'
  }
})


在这里插入图片描述
【注意】这个持久化存储是自动存储的,什么时机呢?在你使用store的时候。

选择性持久化数据

大部分时候 ,store里的数据只需要存储一部分数据。
persist 还接受一个数组。可以选择性的存储部分数据

import { defineStore } from 'pinia'

defineStore('store', {
  state: () => ({
    toLocal: '',
    toSession: '',
    toNowhere: '',
  }),
  persist: [
    {
      paths: ['toLocal'],
      storage: localStorage,
    },
    {
      paths: ['toSession'],
      storage: sessionStorage,
    },
  ],
})

示例:

/*
 * @Date: 2022-11-30 17:26:39
 * @LastEditors: zhangsk
 * @LastEditTime: 2023-04-14 13:42:52
 * @FilePath: \basic-demo\src\store\index.ts
 * @Label: Do not edit
 */
import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  //  类似data
  state: () => {
    return {
      userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo') as string) : undefined,
      token: 'aaxswkjaoksjdohasdh' as string | undefined,
      num: 1,
    }
  },
  //  类似计算属性
  getters: {
    getNum2: (state) => state.num * 2
  },
  // 类似methods
  actions: {
    setUserInfo(info = null) {
      this.userInfo = info || undefined
      console.log(info);

      localStorage.setItem('userInfo', JSON.stringify(info))
    }
  },
  persist: [
    {
      paths: ['num'],
      storage: sessionStorage,
      key: 'my_num'
    },
    {
      paths: ['token'],
      key: 'token',
      storage: localStorage
    },
  ]
})


在这里插入图片描述

注意

由于数据将会被序列化,因此非基本类型(如 Date)不会以 Date 对象形式存储,而是作为 string。
当提供自定义 storage 时,其方法必须是同步的,这是因为 Pinia 的状态订阅($subscribe)是同步的(与 mutations 一致)。

结语

结束了。

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我会为您提供 Pinia 数据持久化储存插件(pinia-plugin-persistedstate)的详细代码配置。 首先,您需要安装 `pinia-plugin-persistedstate` 插件: ``` npm install pinia-plugin-persistedstate ``` 然后,在您的 Vue.js 项目中,您需要创建一个 Pinia 实例,并使用 `use` 方法加载 `pinia-plugin-persistedstate` 插件: ```javascript import { createPinia } from 'pinia' import { createPersistedState } from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(createPersistedState({ key: 'my-app-state', // 存储在本地存储中的键名 initialState: () => ({ // 初始状态 count: 0, todos: [] }), storage: window.localStorage // 存储在哪个存储中(可选) })) ``` 以上代码中,我们使用了 `createPersistedState` 方法创建一个持久化状态插件实例,并将其传递给 `pinia.use()` 方法以加载插件。 在 `createPersistedState` 方法中,您需要传递一个对象参数,包含以下选项: - `key`:在本地存储存储状态的键名。 - `initialState`:状态的初始值。这可以是一个对象或一个函数,该函数返回一个对象。 - `storage`:指定存储状态的存储对象。默认是 `window.localStorage`。 现在,您可以在 Pinia store 中使用持久状态了。例如: ```javascript import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ }, decrement() { this.count-- } } }) ``` 以上代码中,我们定义了一个简单的计数器存储。现在,我们可以在组件中使用 `useCounterStore`: ```html <template> <div> <p>Count: {{ count }}</p> <button @click="increment">+</button> <button @click="decrement">-</button> </div> </template> <script> import { useCounterStore } from './store' export default { setup() { const counterStore = useCounterStore() return { count: counterStore.count, increment: counterStore.increment, decrement: counterStore.decrement } } } </script> ``` 现在,每当用户增加或减少计数器时,状态都会自动持久化到本地存储中。当用户刷新页面或重新打开应用程序时,状态将从本地存储中自动加载。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZSK6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值