index.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { createPinia } from 'pinia'
  2. import { createPersistedState } from 'pinia-plugin-persistedstate' // 数据持久化
  3. import common from './common'
  4. import user from './user'
  5. import webapi from './webapi'
  6. import curPage from './curPage'
  7. /** 存储初始化 */
  8. export const initStore = createPinia()
  9. initStore.use(
  10. createPersistedState({
  11. storage: {
  12. getItem: uni.getStorageSync,
  13. setItem: uni.setStorageSync,
  14. },
  15. }),
  16. )
  17. const stores = {
  18. common,
  19. user,
  20. webapi,
  21. curPage,
  22. }
  23. // 子属性直接为其返回类型
  24. type StoreReturnType<T> = {
  25. [P in keyof T]: GetReturnType<T[P]>
  26. }
  27. // 缓存对象 减少重复执行
  28. const _store = {}
  29. /** 由于 defineStore 需要pinia安装后才能使用,使用代理在使用时再获取对应的defineStore。
  30. 否则会报错: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?
  31. */
  32. const storesProxy = new Proxy<StoreReturnType<typeof stores>>(stores as any, {
  33. get(target, p) {
  34. if (target[p]) {
  35. if (!_store[p]) {
  36. _store[p] = target[p]()
  37. }
  38. return _store[p]
  39. }
  40. },
  41. })
  42. export default storesProxy