feat(projects): 增加pinia数据持久化插件,持久化主题配置

This commit is contained in:
zxdstyle 2022-05-10 11:02:09 +08:00
parent 60f912508b
commit 7a2b1613ff
3 changed files with 34 additions and 0 deletions

View File

@ -1,9 +1,11 @@
import type { App } from 'vue';
import { createPinia } from 'pinia';
import { keepStorage } from './plugins';
/** setup vue store plugin: pinia. - [安装vue状态管理插件pinia] */
export function setupStore(app: App) {
const store = createPinia();
store.use(keepStorage({ key: 'pinia', needKeepIds: ['theme-store'] }));
app.use(store);
}

View File

@ -0,0 +1,3 @@
import keepStorage from './keepStorage';
export { keepStorage };

View File

@ -0,0 +1,29 @@
import { toRaw } from 'vue';
import { PiniaCustomProperties, PiniaCustomStateProperties, PiniaPluginContext } from 'pinia';
import { getLocal, setLocal } from '@/utils/storage';
type Options = {
key: string;
needKeepIds?: string[];
};
const keepStorage = (options: Options) => {
const { key, needKeepIds = [] } = options;
return (context: PiniaPluginContext): Partial<PiniaCustomProperties & PiniaCustomStateProperties> => {
const { store } = context;
const data = getLocal(`${key ?? 'pinia'}-${store.$id}`) as Object;
if (needKeepIds.length === 0) {
store.$subscribe(() => {
setLocal(`${key ?? 'pinia'}-${store.$id}`, toRaw(store.$state));
});
} else if (needKeepIds.includes(store.$id)) {
store.$subscribe(() => {
setLocal(`${key ?? 'pinia'}-${store.$id}`, toRaw(store.$state));
});
}
return { ...data };
};
};
export default keepStorage;