pinia-实现一个pinia持久化插件

2,073 阅读2分钟

前端小伙伴,对于pinia应该不陌生了吧,Pinia.js是由Vue.js团队核心成员开发的新一代状态管理器,使用Composition Api进行重新设计的,也被视为下一代Vuex。Pinia是一个Vue的状态管理库,允许跨组件、跨页面进行全局共享状态,也由于其设计的简洁性、和对typescript的良好支持,取代Vuex指日可待。使用后真的回不去vuex了,它简直可爱、简约、轻量到1kb

把官网地址贴到这里,pinia.vuejs.org/introductio…

好了,它的有点介绍完了,我们开始今天的pinia持久化插件了 (这里为了篇幅,就直接从项目搭建完,且安装好了pinia开始)

一、新建store

在src文件下新建store文件夹,并下下面新建main.ts文件

image.png

import { defineStore } from "pinia"

type User = {
  name: string
  age: number
}

export const useTestStore = defineStore({
  id: "testStore",
  state: () => ({
    user: <User>{
      name: "pmy",
      age: 18,
    },
    name: "pmy",
  }),
})

export const useTestStore1 = defineStore({
  id: "testStore1",
  state: () => ({
    work: "",
  }),
})

二、main.ts中引入pinia 并进行持久化处理

import { createApp } from "vue"
import App from "./App.vue"
import { createPinia } from "pinia"
import piniaPlugin from "./store/plugin" //这是今天的主角,我将它提到一个文件中

const app = createApp(App)

const store = createPinia()
store.use(
  piniaPlugin({
    key: "pinia", // 这是给缓存到本地时,加一个特殊的前缀,以免造成污染到其他缓存数据
    needKeepIds: ["testStore"], // 对于特定store进行持久化,空或者不传,则对所有的store进行缓存到本地
  }),
)

app.use(store).mount("#app")

三、本文的主角 piniaPlugin.ts

这里会用到 pinia的监听subscribestate中的数据变化时,就会触发subscribe,state中的数据变化时,就会触发subscribe,这样我们就可以判断当前变化的store的id,是否在我们的需要持久化的数组中,如果在,我们就将数据存到本地缓存

import { getStorage, setStorage } from "@/utils/utils"
import { PiniaPluginContext } from "pinia"
import { toRaw } from "vue"

type Options = {
  key: string
  needKeepIds?: string[]
}

const piniaPlugin = (options: Options) => {
  const { key, needKeepIds = [] } = options
  return (context: PiniaPluginContext) => {
    const { store } = context
    const data = getStorage(`${key ?? "pinia"}-${store.$id}`)
    if (needKeepIds.length === 0) {
      store.$subscribe(() => {
        setStorage(`${key ?? "pinia"}-${store.$id}`, toRaw(store.$state))
      })
    } else {
      needKeepIds.includes(store.$id) &&
        store.$subscribe(() => {
          setStorage(`${key ?? "pinia"}-${store.$id}`, toRaw(store.$state))
        })
    }

    return {
      ...data,
    }
  }
}

export default piniaPlugin

好了,到这里就已经完成了,现在我们store中的state数据就能得到保持了,刷新也能保持最新的数据

这其实是我在博客看到的一个很好的博主的文章,学习后的梳理,有兴趣大家可以去学习,博客搜小满zs