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' },
              ]"
/>
相关推荐
一个懒人懒人几秒前
Promise async/await与fetch的概念
前端·javascript·html
Mintopia7 分钟前
Web 安全与反编译源码下的权限设计:构筑前后端一致的防护体系
前端·安全
输出输入9 分钟前
前端核心技术
开发语言·前端
Mintopia13 分钟前
Web 安全与反编译源码下的权限设计:构建前后端一体的信任防线
前端·安全·编译原理
林深现海34 分钟前
Jetson Orin nano/nx刷机后无法打开chrome/firefox浏览器
前端·chrome·firefox
EchoEcho1 小时前
深入理解 Vue.js 渲染机制:从声明式到虚拟 DOM 的完整实现
vue.js
黄诂多1 小时前
APP原生与H5互调Bridge技术原理及基础使用
前端
前端市界1 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
文艺理科生1 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
前端·后端·架构
千寻girling1 小时前
主管:”人家 Node 框架都用 Nest.js 了 , 你怎么还在用 Express ?“
前端·后端·面试