vue3 封装一个在el-table中回显字典的组件

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' },
              ]"
/>
相关推荐
代码搬运媛6 分钟前
Jest 测试框架详解与实现指南
前端
counterxing1 小时前
我把 Codex 里的 Skills 做成了一个 MCP,还支持分享
前端·agent·ai编程
wangqiaowq1 小时前
windows下nginx的安装
linux·服务器·前端
之歆1 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
发现一只大呆瓜2 小时前
Vite凭什么这么快?3分钟带你彻底搞懂 Vite 热更新的幕后黑手
前端·面试·vite
Maimai108082 小时前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
candyTong2 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
kyriewen3 小时前
产品经理把PRD写成“天书”,我用AI半小时重写了一遍,他当场愣住
前端·ai编程·cursor
humcomm4 小时前
元框架的工作原理详解
前端·前端框架
canonical_entropy4 小时前
Attractor Before Harness: AI 大规模开发的方法论
前端·aigc·ai编程