pinia 持久化插件

复制代码
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// import SelfComponent from './study/selfComponent/component.vue'
// import 'animate.css';
// import mitt from 'mitt';
// const Mit = mitt();
// // TypeScript 注册
// // 通过ComponentCustomProperties拓展类型才能有类型提示
// declare module "Vue" {
//   export interface ComponentCustomProperties {
//     $Bus: typeof Mit;
//     $env: string
//   }
// }

const app = createApp(App)
// app.component('SelfComponent', SelfComponent) // 注册全局组件
// // 全局变量和函数定义,vue2的property已经废除
// app.config.globalProperties.$Bus = mitt(); // 全局事件总线
// app.config.globalProperties.$filters = {
//   format: (target:string) => {
//     return 'demo' + target
//   }
// }
// import Loading from './study/Loading';  // 引入插件,如果插件是npm安装的,则为import Loading from 'Loding'
// app.use(Loading) // 插件使用
app.config.globalProperties.$env = 'dev'

import {createPinia} from 'pinia'
const store = createPinia()

import type {PiniaPluginContext} from 'pinia'

type options ={
  key: string
}
const setStorage = (key:string, value:any) => {
  localStorage.setItem(key, JSON.stringify(value))
}
const getStorage = (key:string) => {
  return JSON.parse(localStorage.getItem(key) ?? '{}')
}
const __pinnia__ = '__pinnia__'
const piniaContext = (options:options) => {
  return (context:PiniaPluginContext) => {
    // console.log(context); // 有多少个store被创建,就会执行多少次,context是store的上下文
    const {store} = context
    // $state是响应式对象,存储到localStorage用原生数据
    const state = toRaw(store.$state)
    // 获取localStorage数据
    const data = getStorage(`${options.key ?? __pinnia__}-${store.$id}`)
    // 订阅state变动时,存储到localStorage
    store.$subscribe(() => {
        // 设置localStorage的key为前缀+不同的store.$id
        setStorage(`${options.key ?? __pinnia__}-${store.$id}`, state)
      }
    )
    // 拦截从state获取数据,返回localStorage数据
    return data
  }
}
// pinia引入插件也是用的use
// key做存储loaclStorage前缀
store.use((piniaContext({key: 'test'})))
app.use(store)
app.mount('#app')
复制代码

 

posted on   ChoZ  阅读(22)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2023-02-22 Vue3中使用JSX简明语法
2023-02-22 TS补充笔记

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示