From 07efc20ea2aa150c4e4620a49cede884277a2ff3 Mon Sep 17 00:00:00 2001 From: keven1024 Date: Sun, 13 Apr 2025 22:16:32 +0800 Subject: [PATCH] feat(front): add Pinia for state management and create useStore composable for improved state handling --- front/composables/useStore.ts | 35 +++++++++++++++++++++++++++++++++++ front/nuxt.config.ts | 1 + front/package.json | 1 + 3 files changed, 37 insertions(+) create mode 100644 front/composables/useStore.ts diff --git a/front/composables/useStore.ts b/front/composables/useStore.ts new file mode 100644 index 0000000..feaa37e --- /dev/null +++ b/front/composables/useStore.ts @@ -0,0 +1,35 @@ +import { defineStore } from 'pinia' +import { cloneDeep, get, isEmpty, isUndefined, set,isString } from 'lodash-es' + +type StoreType = Record + +const initState: StoreType = {} +// 做了一点小小的改进,可以传入key,会自动初始化,如果不初始化的话容易导致不存在值而丢失响应式 +const useStore = (key?: string) => { + const store = defineStore('store', { + state: () => ({ + ...initState, + }), + actions: { + _get(path?: string) { + if (isEmpty(path) || isUndefined(path)) { + return this.$state + } + return get(this.$state, path) + }, + _set(path: string, value: any) { + const newState = cloneDeep(this.$state) + set(newState, path, value) + this.$patch(newState) + }, + }, + persist: true, + })() + if (!isEmpty(key) && isString(key) && isUndefined(store?._get(key))) { + console.log('reset', key, store?._get(key)) + store?._set(key, undefined) + } + return store +} + +export default useStore diff --git a/front/nuxt.config.ts b/front/nuxt.config.ts index 7477bff..36f792a 100644 --- a/front/nuxt.config.ts +++ b/front/nuxt.config.ts @@ -94,6 +94,7 @@ export default defineNuxtConfig({ "nuxt-lucide-icons", "shadcn-nuxt", '@vee-validate/nuxt', + '@pinia/nuxt', ], serwist: {}, vite: { diff --git a/front/package.json b/front/package.json index ee58826..c5777d8 100644 --- a/front/package.json +++ b/front/package.json @@ -10,6 +10,7 @@ "postinstall": "nuxt prepare" }, "dependencies": { + "@pinia/nuxt": "^0.11.0", "@tailwindcss/postcss": "^4.1.3", "@tailwindcss/vite": "^4.1.3", "@tiptap/extension-blockquote": "^2.11.7",