diff --git a/src/hooks/business/dict.ts b/src/hooks/business/dict.ts index 4f6cf0d2..5ebc17a0 100644 --- a/src/hooks/business/dict.ts +++ b/src/hooks/business/dict.ts @@ -2,41 +2,55 @@ import { ref } from 'vue'; import { fetchGetDictDataByType } from '@/service/api'; import { useDictStore } from '@/store/modules/dict'; -export function useDict() { +export function useDict(dictType: string, immediate: boolean = true) { const dictStore = useDictStore(); - async function getDictData(dictType: string) { + const data = ref([]); + const record = ref>({}); + const options = ref([]); + + async function getData() { const dicts = dictStore.getDict(dictType); if (dicts) { - return dicts; + data.value = dicts; + return; } - const { data, error } = await fetchGetDictDataByType(dictType); - if (error) return []; - dictStore.setDict(dictType, data); - return data; + const { data: dictData, error } = await fetchGetDictDataByType(dictType); + if (error) return; + dictStore.setDict(dictType, dictData); + data.value = dictData; } - function getDictRecord(dictType: string) { - const dictRecord = ref<{ [key: string]: string }>({}); - getDictData(dictType).then(dictData => { - dictData.forEach(dict => { - dictRecord.value[dict.dictValue!] = dict.dictLabel!; - }); + async function getRecord() { + if (!data.value.length) { + await getData(); + } + data.value.forEach(dict => { + record.value[dict.dictValue!] = dict.dictLabel!; }); - return dictRecord; } - function getDictOptions(dictType: string) { - const dictOptions = ref([]); - getDictData(dictType).then(dictData => { - dictOptions.value = dictData.map(dict => ({ label: dict.dictLabel!, value: dict.dictValue! })); + async function getOptions() { + if (!data.value.length) { + await getData(); + } + + options.value = data.value.map(dict => ({ label: dict.dictLabel!, value: dict.dictValue! })); + } + + if (immediate) { + getData().then(() => { + getRecord(); + getOptions(); }); - return dictOptions; } return { - getDictData, - getDictRecord, - getDictOptions + data, + record, + options, + getData, + getRecord, + getOptions }; } diff --git a/src/views/system/menu/index.vue b/src/views/system/menu/index.vue index 84b0df5e..dc0ef3ff 100644 --- a/src/views/system/menu/index.vue +++ b/src/views/system/menu/index.vue @@ -259,8 +259,7 @@ const btnColumns: DataTableColumns = [ } ]; -const { getDictRecord } = useDict(); -const showHideRecord = getDictRecord('sys_show_hide'); +const { record: showHideRecord } = useDict('sys_show_hide');