setup.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import type { Pinia } from 'pinia';
  2. import type { App } from 'vue';
  3. import { createPinia } from 'pinia';
  4. let pinia: Pinia;
  5. export interface InitStoreOptions {
  6. /**
  7. * @zh_CN 应用名,由于 @vben/stores 是公用的,后续可能有多个app,为了防止多个app缓存冲突,可在这里配置应用名,应用名将被用于持久化的前缀
  8. */
  9. namespace: string;
  10. }
  11. /**
  12. * @zh_CN 初始化pinia
  13. */
  14. export async function initStores(app: App, options: InitStoreOptions) {
  15. const { createPersistedState } = await import('pinia-plugin-persistedstate');
  16. pinia = createPinia();
  17. const { namespace } = options;
  18. pinia.use(
  19. createPersistedState({
  20. // key $appName-$store.id
  21. key: (storeKey) => `${namespace}-${storeKey}`,
  22. storage: localStorage,
  23. }),
  24. );
  25. app.use(pinia);
  26. return pinia;
  27. }
  28. export function resetAllStores() {
  29. if (!pinia) {
  30. console.error('Pinia is not installed');
  31. return;
  32. }
  33. const allStores = (pinia as any)._s;
  34. for (const [_key, store] of allStores) {
  35. store.$reset();
  36. }
  37. }