Files

137 lines
2.8 KiB
TypeScript
Raw Permalink Normal View History

2025-07-21 16:47:04 +08:00
import { reactive } from "vue";
import { request } from "../service";
2025-07-21 16:47:04 +08:00
import { forInObject, isNull, parse } from "../utils";
// 字典项类型定义
export type DictItem = {
id: number; // 字典项ID
typeId: number; // 字典类型ID
label: string; // 显示标签
name: string; // 可选名称
value: any; // 字典项值
orderNum: number; // 排序号
parentId?: number | null; // 父级ID可选
};
// 字典数据类型定义
export type DictData = {
key: string; // 字典key
list: DictItem[]; // 字典项列表
};
// 字典管理类
export class Dict {
private data: DictData[] = reactive([]); // 存储所有字典数据
constructor() {}
/**
* key的字典数据
* @param key key
* @returns
*/
find(key: string) {
return this.data.find((e) => e.key == key);
}
/**
* key的字典项列表
* @param key key
* @returns
*/
get(key: string): DictItem[] {
2025-07-21 16:47:04 +08:00
return this.find(key)?.list ?? new Array<DictItem>();
}
/**
* key和value的字典项
* @param key key
* @param value
* @returns null
*/
getItem(key: string, value: any): DictItem | null {
2025-07-21 16:47:04 +08:00
const item = this.get(key).find((e) => e.value == value);
if (isNull(item)) {
return null;
}
return item!;
}
/**
* key和多个value的字典项数组
* @param key key
* @param values
* @returns
*/
getItems(key: string, values: any[]): DictItem[] {
2025-07-21 16:47:04 +08:00
return values.map((e) => this.getItem(key, e)).filter((e) => !isNull(e)) as DictItem[];
}
/**
* key和value的字典项的label
* @param key key
* @param value
* @returns label字符串
*/
getItemLabel(key: string, value: any): string {
2025-07-21 16:47:04 +08:00
const item = this.getItem(key, value);
if (isNull(item) || isNull(item?.label)) {
return "";
}
return item!.label;
}
/**
*
* @param types key数组
*/
async refresh(types?: string[] | null): Promise<void> {
const res = await request({
url: "/app/dict/info/data",
method: "POST",
data: { types }
});
if (res == null) {
return;
}
2025-07-21 16:47:04 +08:00
// 遍历返回的字典数据
forInObject(res, (arr, key) => {
let list: DictItem[] = [];
(arr as UTSJSONObject[]).forEach((e) => {
e["label"] = e["name"];
const d = parse<DictItem>(e);
if (d != null) {
list.push(d);
}
});
const item = this.find(key);
// 如果不存在则新增,否则更新
if (isNull(item)) {
this.data.push({
key,
list
});
} else {
item!.list = list;
}
});
// #ifdef H5
console.log("[DICT]", this.data);
// #endif
}
}
// 单例字典对象
export const dict = new Dict();