ruoyi-plus-soybean/src/hooks/business/dict.ts
2024-09-11 16:37:35 +08:00

76 lines
1.8 KiB
TypeScript

import { ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { fetchGetDictDataByType } from '@/service/api/system';
import { useDictStore } from '@/store/modules/dict';
export function useDict(dictType: string, immediate: boolean = true) {
const dictStore = useDictStore();
const { dictData: dictList } = storeToRefs(dictStore);
const data = ref<Api.System.DictData[]>([]);
const record = ref<Record<string, string>>({});
const options = ref<CommonType.Option[]>([]);
async function getData() {
const dicts = dictStore.getDict(dictType);
if (dicts) {
data.value = dicts;
return;
}
const { data: dictData, error } = await fetchGetDictDataByType(dictType);
if (error) return;
dictStore.setDict(dictType, dictData);
data.value = dictData;
}
async function getRecord() {
if (!data.value.length) {
await getData();
}
data.value.forEach(dict => {
record.value[dict.dictValue!] = dict.dictLabel!;
});
}
async function getOptions() {
if (!data.value.length) {
await getData();
}
options.value = data.value.map(dict => ({ label: dict.dictLabel!, value: dict.dictValue! }));
}
function transformDictData(dictValue: string): Api.System.DictData | undefined {
if (!data.value.length || !dictValue) return undefined;
return data.value.find(dict => dict.dictValue === dictValue);
}
if (immediate) {
getData().then(() => {
getRecord();
getOptions();
});
} else {
watch(
() => dictList.value[dictType],
val => {
if (val && val.length) {
getRecord();
getOptions();
}
},
{ immediate: true }
);
}
return {
data,
record,
options,
getData,
getRecord,
getOptions,
transformDictData
};
}