diff --git a/src/store/index.ts b/src/store/index.ts index 74cdcb05..0a39554b 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -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); } diff --git a/src/store/plugins/index.ts b/src/store/plugins/index.ts new file mode 100644 index 00000000..946531fa --- /dev/null +++ b/src/store/plugins/index.ts @@ -0,0 +1,3 @@ +import keepStorage from './keepStorage'; + +export { keepStorage }; diff --git a/src/store/plugins/keepStorage.ts b/src/store/plugins/keepStorage.ts new file mode 100644 index 00000000..c8efa1c6 --- /dev/null +++ b/src/store/plugins/keepStorage.ts @@ -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 => { + 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;