From 7a2b1613ff66be0a177715a7c7caaddeb40ea539 Mon Sep 17 00:00:00 2001 From: zxdstyle <1430822515@qq.com> Date: Tue, 10 May 2022 11:02:09 +0800 Subject: [PATCH] =?UTF-8?q?feat(projects):=20=E5=A2=9E=E5=8A=A0pinia?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E6=8C=81=E4=B9=85=E5=8C=96=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=EF=BC=8C=E6=8C=81=E4=B9=85=E5=8C=96=E4=B8=BB=E9=A2=98=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/store/index.ts | 2 ++ src/store/plugins/index.ts | 3 +++ src/store/plugins/keepStorage.ts | 29 +++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 src/store/plugins/index.ts create mode 100644 src/store/plugins/keepStorage.ts 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;