vue3 封装一个在el-table中回显字典的组件
MyDictTag.vue
html
<template>
<el-tag :type="tagType" :effect="effect">
{{ displayText }}
</el-tag>
</template>
<script setup>
import { computed } from 'vue';
const props = defineProps({
// 字典值
value: {
type: [String, Number],
required: true,
},
// 字典数据
dictData: {
type: [Array, Object],
default: () => [],
},
// 未匹配时的默认显示
emptyText: {
type: String,
default: '-',
},
//主题:dark、light 和 plain。
effect: {
type: String,
default: 'light',
},
});
const displayText = computed(() => {
if (props.value == null || props.value === '') {
return props.emptyText;
}
const val = String(props.value);
// 情况1:dict 是对象 { '1': '男', '2': '女' }
if (typeof props.dictData === 'object' && !Array.isArray(props.dictData)) {
return props.dictData[val] ?? props.emptyText;
}
// 情况2:dict 是数组 [{ value: '1', label: '男' }, ...]
if (Array.isArray(props.dictData)) {
const item = props.dictData.find((d) => String(d.value) === val);
return item ? item.label : props.emptyText;
}
return props.emptyText;
});
const tagType = computed(() => {
const successList = ['已批准', '已提交', '进行中', '已归档', '已通过', '已审批', '借阅中', '男', '公告'];
const dangerList = ['已拒绝', '已取消', '已驳回', '已禁用', '停用', '否', '删除', '失败'];
const warningList = ['待审核', '待处理', '待确认', '待反馈', '待评价', '待归档', '待开始', '待审批', '女', '通知', '导入'];
const infoList = ['已完成', '已删除', '已审核', '已归还', '已关闭', '修改'];
if (successList.includes(displayText.value)) {
return 'success';
} else if (dangerList.includes(displayText.value)) {
return 'danger';
} else if (warningList.includes(displayText.value)) {
return 'warning';
} else if (infoList.includes(displayText.value)) {
return 'info';
} else {
return 'primary';
}
});
</script>
- 使用
html
<MyDictTag value="0" :dictData="[
{ label: '待审核', value: '0' },
{ label: '已批准', value: '1' },
]"
/>