72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
|
|
import useDictStore from "@/store/modules/dict";
|
||
|
|
import { getDicts } from "@/api/system/dict/data";
|
||
|
|
import { Ref, ref, toRefs } from "vue";
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 获取字典数据
|
||
|
|
*/
|
||
|
|
export function useDict(...args : any[]) {
|
||
|
|
const res : Ref<any> = ref({});
|
||
|
|
return (() => {
|
||
|
|
args.forEach((dictType, index) => {
|
||
|
|
// console.log(dictType)
|
||
|
|
res.value[dictType] = [];
|
||
|
|
const dicts = useDictStore().getDict(dictType);
|
||
|
|
if (dicts) {
|
||
|
|
res.value[dictType] = dicts;
|
||
|
|
} else {
|
||
|
|
// console.log(111)
|
||
|
|
getDicts(dictType).then((resp) => {
|
||
|
|
// console.log(111)
|
||
|
|
// console.log(resp)
|
||
|
|
res.value[dictType] = resp.data.map((p : any) => ({
|
||
|
|
label: p.dictLabel,
|
||
|
|
value: p.dictValue,
|
||
|
|
elTagType: p.listClass,
|
||
|
|
elTagClass: p.cssClass,
|
||
|
|
}));
|
||
|
|
useDictStore().setDict(dictType, res.value[dictType]);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
});
|
||
|
|
// console.log(res.value)
|
||
|
|
return toRefs(res.value);
|
||
|
|
})();
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 获取单个字典数据
|
||
|
|
*/
|
||
|
|
export async function getDict(dictType) {
|
||
|
|
const dictStore = useDictStore();
|
||
|
|
const cachedDict = dictStore.getDict(dictType);
|
||
|
|
|
||
|
|
if (cachedDict) {
|
||
|
|
return cachedDict;
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
const resp = await getDicts(dictType);
|
||
|
|
const dictData = resp.data.map((p) => ({
|
||
|
|
label: p.dictLabel,
|
||
|
|
value: p.dictValue,
|
||
|
|
elTagType: p.listClass,
|
||
|
|
elTagClass: p.cssClass,
|
||
|
|
}));
|
||
|
|
|
||
|
|
dictStore.setDict(dictType, dictData);
|
||
|
|
return dictData;
|
||
|
|
} catch (error) {
|
||
|
|
console.error(`获取字典 ${dictType} 失败:`, error);
|
||
|
|
return [];
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 获取字典标签
|
||
|
|
*/
|
||
|
|
export async function getDictLabel(dictType, dictValue) {
|
||
|
|
const dictData = await getDict(dictType);
|
||
|
|
const item = dictData.find(d => d.value === dictValue);
|
||
|
|
return item ? item.label : dictValue;
|
||
|
|
}
|