Files
admin-vben5/apps/web-antd/src/store/dict.ts

110 lines
2.8 KiB
TypeScript
Raw Normal View History

2025-06-18 11:03:42 +08:00
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type { DictData } from '#/api/system/dict/dict-data-model';
import { reactive } from 'vue';
import { defineStore } from 'pinia';
/**
* antd使用 select和radio通用
* DictData的拓展
*/
export interface DictOption extends DictData {
disabled?: boolean;
label: string;
value: number | string;
}
/**
* Options
* @param data
* @param formatNumber value格式化为number类型
* @returns options
*/
export function dictToOptions(
data: DictData[],
formatNumber = false,
): DictOption[] {
return data.map((item) => ({
...item,
label: item.dictLabel,
value: formatNumber ? Number(item.dictValue) : item.dictValue,
}));
}
export const useDictStore = defineStore('app-dict', () => {
/**
* select radio checkbox等使用 {label, value}
*/
const dictOptionsMap = reactive(new Map<string, DictOption[]>());
/**
*
*
* api的问题(abortController )
* index表单 modal drawer总共会请求三次
*
*/
const dictRequestCache = reactive(
new Map<string, Promise<DictData[] | void>>(),
);
function getDictOptions(dictName: string): DictOption[] {
if (!dictName) return [];
// 没有key 添加一个空数组
if (!dictOptionsMap.has(dictName)) {
dictOptionsMap.set(dictName, []);
}
// 这里拿到的就不可能为空了
return dictOptionsMap.get(dictName)!;
}
function resetCache() {
dictRequestCache.clear();
dictOptionsMap.clear();
/**
* dictRequestCache /key
*/
}
/**
*
*
* 使set return的空数组跟现在的数组指向不是同一个地址
*
* key 0 return的空数组 push()
* set
*
*/
function setDictInfo(
dictName: string,
dictValue: DictData[],
formatNumber = false,
) {
if (
dictOptionsMap.has(dictName) &&
dictOptionsMap.get(dictName)?.length === 0
) {
dictOptionsMap
.get(dictName)
?.push(...dictToOptions(dictValue, formatNumber));
} else {
dictOptionsMap.set(dictName, dictToOptions(dictValue, formatNumber));
}
}
function $reset() {
/**
* doNothing
*/
}
return {
$reset,
dictOptionsMap,
dictRequestCache,
getDictOptions,
resetCache,
setDictInfo,
};
});