2024-07-23 00:03:59 +08:00
|
|
|
|
import type { Pinia } from 'pinia';
|
|
|
|
|
|
2024-07-30 21:10:28 +08:00
|
|
|
|
import type { App } from 'vue';
|
|
|
|
|
|
2024-07-23 00:03:59 +08:00
|
|
|
|
import { createPinia } from 'pinia';
|
2025-04-27 20:59:10 +08:00
|
|
|
|
import SecureLS from 'secure-ls';
|
2024-07-23 00:03:59 +08:00
|
|
|
|
|
|
|
|
|
let pinia: Pinia;
|
|
|
|
|
|
|
|
|
|
export interface InitStoreOptions {
|
|
|
|
|
/**
|
|
|
|
|
* @zh_CN 应用名,由于 @vben/stores 是公用的,后续可能有多个app,为了防止多个app缓存冲突,可在这里配置应用名,应用名将被用于持久化的前缀
|
|
|
|
|
*/
|
|
|
|
|
namespace: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @zh_CN 初始化pinia
|
|
|
|
|
*/
|
2024-07-30 21:10:28 +08:00
|
|
|
|
export async function initStores(app: App, options: InitStoreOptions) {
|
2024-07-23 00:03:59 +08:00
|
|
|
|
const { createPersistedState } = await import('pinia-plugin-persistedstate');
|
|
|
|
|
pinia = createPinia();
|
|
|
|
|
const { namespace } = options;
|
2025-04-27 20:59:10 +08:00
|
|
|
|
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`,
|
|
|
|
|
});
|
2024-07-23 00:03:59 +08:00
|
|
|
|
pinia.use(
|
|
|
|
|
createPersistedState({
|
|
|
|
|
// key $appName-$store.id
|
|
|
|
|
key: (storeKey) => `${namespace}-${storeKey}`,
|
2025-04-27 20:59:10 +08:00
|
|
|
|
storage: import.meta.env.DEV
|
|
|
|
|
? localStorage
|
|
|
|
|
: {
|
|
|
|
|
getItem(key) {
|
|
|
|
|
return ls.get(key);
|
|
|
|
|
},
|
|
|
|
|
setItem(key, value) {
|
|
|
|
|
ls.set(key, value);
|
|
|
|
|
},
|
|
|
|
|
},
|
2024-07-23 00:03:59 +08:00
|
|
|
|
}),
|
|
|
|
|
);
|
2024-07-30 21:10:28 +08:00
|
|
|
|
app.use(pinia);
|
2024-07-23 00:03:59 +08:00
|
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
}
|