Files
015/front/composables/useStore.ts

36 lines
1021 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { defineStore } from 'pinia'
import { cloneDeep, get, isEmpty, isUndefined, set,isString } from 'lodash-es'
type StoreType = Record<string, any>
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