admin-vben5/packages/stores/src/setup.ts

61 lines
1.5 KiB
TypeScript
Raw Normal View History

import type { Pinia } from 'pinia';
2024-07-30 21:10:28 +08:00
import type { App } from 'vue';
import { createPinia } from 'pinia';
import SecureLS from 'secure-ls';
let pinia: Pinia;
export interface InitStoreOptions {
/**
* @zh_CN , @vben/stores appapp缓存冲突,
*/
namespace: string;
}
/**
* @zh_CN pinia
*/
2024-07-30 21:10:28 +08:00
export async function initStores(app: App, options: InitStoreOptions) {
const { createPersistedState } = await import('pinia-plugin-persistedstate');
pinia = createPinia();
const { namespace } = options;
const ls = new SecureLS({
encodingType: 'aes',
encryptionSecret: import.meta.env.VITE_APP_STORE_SECURE_KEY,
isCompression: true,
// @ts-ignore secure-ls does not have a type definition for this
metaKey: `${namespace}-secure-meta`,
});
pinia.use(
createPersistedState({
// key $appName-$store.id
key: (storeKey) => `${namespace}-${storeKey}`,
storage: import.meta.env.DEV
? localStorage
: {
getItem(key) {
return ls.get(key);
},
setItem(key, value) {
ls.set(key, value);
},
},
}),
);
2024-07-30 21:10:28 +08:00
app.use(pinia);
return pinia;
}
export function resetAllStores() {
if (!pinia) {
console.error('Pinia is not installed');
return;
}
const allStores = (pinia as any)._s;
for (const [_key, store] of allStores) {
store.$reset();
}
}