setup.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import type { Pinia } from 'pinia';
  2. import type { App } from 'vue';
  3. import { createPinia } from 'pinia';
  4. import SecureLS from 'secure-ls';
  5. let pinia: Pinia;
  6. export interface InitStoreOptions {
  7. /**
  8. * @zh_CN 应用名,由于 @vben/stores 是公用的,后续可能有多个app,为了防止多个app缓存冲突,可在这里配置应用名,应用名将被用于持久化的前缀
  9. */
  10. namespace: string;
  11. }
  12. /**
  13. * @zh_CN 初始化pinia
  14. */
  15. export async function initStores(app: App, options: InitStoreOptions) {
  16. const { createPersistedState } = await import('pinia-plugin-persistedstate');
  17. pinia = createPinia();
  18. const { namespace } = options;
  19. const ls = new SecureLS({
  20. encodingType: 'aes',
  21. encryptionSecret: import.meta.env.VITE_APP_STORE_SECURE_KEY,
  22. isCompression: true,
  23. // @ts-ignore secure-ls does not have a type definition for this
  24. metaKey: `${namespace}-secure-meta`,
  25. });
  26. pinia.use(
  27. createPersistedState({
  28. // key $appName-$store.id
  29. key: (storeKey) => `${namespace}-${storeKey}`,
  30. storage: import.meta.env.DEV
  31. ? localStorage
  32. : {
  33. getItem(key) {
  34. return ls.get(key);
  35. },
  36. setItem(key, value) {
  37. ls.set(key, value);
  38. },
  39. },
  40. }),
  41. );
  42. app.use(pinia);
  43. return pinia;
  44. }
  45. export function resetAllStores() {
  46. if (!pinia) {
  47. console.error('Pinia is not installed');
  48. return;
  49. }
  50. const allStores = (pinia as any)._s;
  51. for (const [_key, store] of allStores) {
  52. store.$reset();
  53. }
  54. }