Skip to content

Commit

Permalink
feat: add pinia persist plugin (#3173)
Browse files Browse the repository at this point in the history
  • Loading branch information
kirklin authored Oct 19, 2023
1 parent 882270d commit 2152b3f
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"nprogress": "^0.2.0",
"path-to-regexp": "^6.2.1",
"pinia": "2.1.4",
"pinia-plugin-persistedstate": "^3.2.0",
"print-js": "^1.6.0",
"qrcode": "^1.5.3",
"qs": "^6.11.2",
Expand Down
11 changes: 11 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/store/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { App } from 'vue';
import { createPinia } from 'pinia';
import { registerPiniaPersistPlugin } from '@/store/plugin/persist';

const store = createPinia();
registerPiniaPersistPlugin(store);

export function setupStore(app: App<Element>) {
app.use(store);
Expand Down
38 changes: 38 additions & 0 deletions src/store/plugin/persist.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Pinia Persist Plugin
* Pinia 持久化插件
* @link https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/
*
*/
import type { Pinia } from 'pinia';
import { createPersistedState } from 'pinia-plugin-persistedstate';
import type { PersistedStateFactoryOptions } from 'pinia-plugin-persistedstate';
import { getCommonStoragePrefix } from '@/utils/env';

export const PERSIST_KEY_PREFIX = getCommonStoragePrefix();

// TODO customSerializer

/**
* Register Pinia Persist Plugin
* 注册 Pinia 持久化插件
*
* @param pinia Pinia instance Pinia 实例
*/
export function registerPiniaPersistPlugin(pinia: Pinia) {
pinia.use(createPersistedState(createPersistedStateOptions(PERSIST_KEY_PREFIX)));
}

/**
* Create Persisted State Options
* 创建持久化状态选项
*
* @param keyPrefix prefix for storage key 储存键前缀
* @returns persisted state factory options
*/
export function createPersistedStateOptions(keyPrefix: string): PersistedStateFactoryOptions {
return {
storage: localStorage,
key: (id) => `${keyPrefix}__${id}`,
};
}

0 comments on commit 2152b3f

Please sign in to comment.