| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- import { createPinia } from 'pinia'
- import { createPersistedState } from 'pinia-plugin-persistedstate' // 数据持久化
- import common from './common'
- import user from './user'
- import webapi from './webapi'
- import curPage from './curPage'
- /** 存储初始化 */
- export const initStore = createPinia()
- initStore.use(
- createPersistedState({
- storage: {
- getItem: uni.getStorageSync,
- setItem: uni.setStorageSync,
- },
- }),
- )
- const stores = {
- common,
- user,
- webapi,
- curPage,
- }
- // 子属性直接为其返回类型
- type StoreReturnType<T> = {
- [P in keyof T]: GetReturnType<T[P]>
- }
- // 缓存对象 减少重复执行
- const _store = {}
- /** 由于 defineStore 需要pinia安装后才能使用,使用代理在使用时再获取对应的defineStore。
- 否则会报错: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?
- */
- const storesProxy = new Proxy<StoreReturnType<typeof stores>>(stores as any, {
- get(target, p) {
- if (target[p]) {
- if (!_store[p]) {
- _store[p] = target[p]()
- }
- return _store[p]
- }
- },
- })
- export default storesProxy
|