index.ts 1008 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. // https://pinia.vuejs.org/
  2. import { createPinia,PiniaPlugin,PiniaPluginContext } from 'pinia';
  3. import { toRaw } from 'vue'
  4. import {Session} from '/@/utils/storage';
  5. // 数据存储本地
  6. const setStorage = (key: string, value: any) => {
  7. Session.set(key,value)
  8. // sessionStorage.setItem(key, JSON.stringify(value))
  9. }
  10. // 获取本地数据
  11. const getStorage = (key: string) => {
  12. return Session.get(key)
  13. }
  14. const piniaPlugin = (context: PiniaPluginContext) => {
  15. const { store } = context;
  16. // $subscribe state值发生变化时会执行传入的回调
  17. store.$subscribe(() => {
  18. // 每次修改值的时候更新localStorage数据
  19. setStorage(`piniaKey-${store.$id}`, toRaw(store.$state))
  20. })
  21. // 每次构建项目的时候从本地存储取值
  22. const data = getStorage(`piniaKey-${store.$id}`)
  23. // 并将取的值赋给state
  24. return {
  25. ...data
  26. }
  27. }
  28. // 创建
  29. const pinia = createPinia();
  30. pinia.use(piniaPlugin);
  31. // 导出
  32. export default pinia;