长城汽车软件包管理平台
whychdw
2025-04-26 be81587ef4c7a1711884d7ca8f27cbf85e2d7558
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<template>
  <template v-if="tagType">
    <el-tag :type="tagType" :size="tagSize">{{ label }}</el-tag>
  </template>
  <template v-else>
    <span>{{ label }}</span>
  </template>
</template>
<script setup lang="ts">
import { useDictStore } from "@/store";
 
const props = defineProps({
  code: String, // 字典编码
  modelValue: [String, Number], // 字典项的值
  size: {
    type: String,
    default: "default", // 标签大小
  },
});
const label = ref("");
const tagType = ref<"success" | "warning" | "info" | "primary" | "danger" | undefined>(); // 标签类型
const tagSize = ref<"default" | "large" | "small">(props.size as "default" | "large" | "small"); // 标签大小
 
const dictStore = useDictStore();
/**
 * 根据字典项的值获取对应的 label 和 tagType
 * @param dictCode 字典编码
 * @param value 字典项的值
 * @returns 包含 label 和 tagType 的对象
 */
const getLabelAndTagByValue = async (dictCode: string, value: any) => {
  // 按需加载字典数据
  await dictStore.loadDictItems(dictCode);
  // 从缓存中获取字典数据
  const dictItems = dictStore.getDictItems(dictCode);
  // 查找对应的字典项
  const dictItem = dictItems.find((item) => item.value == value);
  return {
    label: dictItem?.label || "",
    tagType: dictItem?.tagType,
  };
};
/**
 * 更新 label 和 tagType
 */
const updateLabelAndTag = async () => {
  console.log("updateLabelAndTag", props.code, props.modelValue);
  if (!props.code || props.modelValue === undefined) return;
  const { label: newLabel, tagType: newTagType } = await getLabelAndTagByValue(
    props.code,
    props.modelValue
  );
  label.value = newLabel;
  tagType.value = newTagType as typeof tagType.value;
};
 
watch([() => props.code, () => props.modelValue], updateLabelAndTag);
 
onMounted(updateLabelAndTag);
</script>