Pinia状态持久化问题怎么解决

其他教程   发布日期:2023年11月07日   浏览次数:448

本篇内容介绍了“Pinia状态持久化问题怎么解决”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

Pinia状态持久化

在vue3中,常用Pinia代替Vuex来进行状态管理。

其他过程就省略了,今天在vue3中实现一个最简单的Pinia持久化插件,后续可能会进一步封装

  1. // FilePath < @/main.ts >
  2. import { createApp, toRaw } from 'vue'
  3. import App from './App.vue'
  4. // 引入pinia
  5. import { createPinia, PiniaPluginContext } from "pinia";
  6. const app = createApp(App)
  7. type Options = {
  8. key?: string
  9. }
  10. // 默认的key
  11. const __piniaKey__: string = 'Ocean'
  12. // 负责存储的函数
  13. const setStorage = (key: string, value: any) => {
  14. // 将对象转字符串后存入 localStorage
  15. localStorage.setItem(key, JSON.stringify(value))
  16. }
  17. // 负责取值的函数
  18. const getStorage = (key: string) => {
  19. // 根据key拿到localStorage中对应的值
  20. return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {}
  21. }
  22. // Pinia持久化插件
  23. const piniaPlugin = (options: Options) => {
  24. return (context: PiniaPluginContext) => {
  25. const { store } = context
  26. const data = getStorage(`${options?.key ?? __piniaKey__}-${store.$id}`)
  27. console.log(data);
  28. store.$subscribe(() => {
  29. // store.$state是一个 proxy 对象 要通过 toRaw() 转换成 原始对象
  30. setStorage(`${options?.key ?? __piniaKey__}-${store.$id}`,toRaw(store.$state))
  31. })
  32. return {
  33. ...data
  34. }
  35. }
  36. }
  37. // 创建一个Pinia实例
  38. const store = createPinia()
  39. // 注册插件
  40. store.use(piniaPlugin({
  41. key: 'pinia'
  42. }))
  43. app.use(store)
  44. app.mount('#app')

Pinia数据持久化处理

1.下载插件pinia-plugin-persist

2.store下的index.js

  1. import { createPinia } from 'pinia'
  2. //pinia 持久化插件
  3. import piniaPluginPersist from 'pinia-plugin-persist'
  4. const store = createPinia()
  5. store.use(piniaPluginPersist)
  6. export default store

在写的store.js文件下增加配置项 默认为sessionStorage

  1. persist: {
  2. enabled: true,
  3. strategies: [
  4. {
  5. key: 'user',
  6. storage: localStorage,
  7. path:[] //可以选择保存的字段 其余的不保存
  8. }
  9. ]
  10. }

以上就是Pinia状态持久化问题怎么解决的详细内容,更多关于Pinia状态持久化问题怎么解决的资料请关注九品源码其它相关文章!