first commit
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import {create, type StateCreator} from 'zustand';
|
||||
import {createJSONStorage, devtools, persist} from 'zustand/middleware';
|
||||
import type {DictMap, DictStore, DictStoreActions, DictStoreState} from './types';
|
||||
import {getAllDict} from '@/api/system/sysDict';
|
||||
|
||||
const dictState: DictStoreState = {
|
||||
dictMap: {}
|
||||
};
|
||||
|
||||
const dictAction: StateCreator<DictStoreState, [], [], DictStoreActions> = (set, get) => ({
|
||||
initDict: async () => {
|
||||
try {
|
||||
const { data } = await getAllDict();
|
||||
const dictMap: DictMap = {};
|
||||
if (data.data) {
|
||||
data.data.forEach((dict) => {
|
||||
if (dict.code && dict.dict_items) {
|
||||
dictMap[dict.code] = dict.dict_items;
|
||||
}
|
||||
});
|
||||
}
|
||||
set({dictMap});
|
||||
} catch (error) {
|
||||
console.error('Failed to load dict data:', error);
|
||||
}
|
||||
},
|
||||
|
||||
getDictItem: (code, value) => {
|
||||
return (get().dictMap[code] || []).find(item => String(item.value) === String(value)) || null;
|
||||
},
|
||||
|
||||
getOptions: (code: string): { label: string; value: string }[] => {
|
||||
const items = get().dictMap[code] || [];
|
||||
return items.map((item) => ({
|
||||
label: item.label || '',
|
||||
value: item.value || '',
|
||||
}));
|
||||
},
|
||||
});
|
||||
|
||||
const useDictStore = create<DictStore>()(
|
||||
devtools(
|
||||
persist(
|
||||
(...args) => ({
|
||||
...dictState,
|
||||
...dictAction(...args),
|
||||
}),
|
||||
{
|
||||
name: 'dict-storage',
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
}
|
||||
),
|
||||
{name: 'XinAdmin-Dict'}
|
||||
)
|
||||
);
|
||||
|
||||
export type {DictStore, DictStoreState, DictStoreActions, DictMap};
|
||||
export default useDictStore;
|
||||
@@ -0,0 +1,23 @@
|
||||
import type {IDictItem} from '@/domain/iDictItem';
|
||||
|
||||
|
||||
/** 字典 Map */
|
||||
export type DictMap = Record<string, IDictItem[]>;
|
||||
|
||||
/** 字典 Store 状态 */
|
||||
export interface DictStoreState {
|
||||
/** 字典数据映射 */
|
||||
dictMap: DictMap;
|
||||
}
|
||||
|
||||
/** 字典 Store 操作 */
|
||||
export interface DictStoreActions {
|
||||
/** 初始化字典数据 */
|
||||
initDict: () => Promise<void>;
|
||||
/** 根据编码获取字典 */
|
||||
getDictItem: (code: string, value?: string | number) => IDictItem | null;
|
||||
/** 获取 Select 选项格式数据 */
|
||||
getOptions: (code: string) => { label: string; value: string }[];
|
||||
}
|
||||
|
||||
export type DictStore = DictStoreState & DictStoreActions;
|
||||
Reference in New Issue
Block a user