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' },
              ]"
/>
相关推荐
华科易迅11 分钟前
Vue如何集成封装Axios
前端·javascript·vue.js
康一夏12 分钟前
Next.js 13变化有多大?
前端·react·nextjs
糖炒栗子032612 分钟前
前端项目标准环境搭建与启动
前端
不是az13 分钟前
CSS知识点记录
前端·javascript·css
爱分享的阿Q21 分钟前
GPT6-Spud-AGI前夜的豪赌
前端·easyui·agi
昵称暂无11 小时前
.NET 高级开发 | i18n 原理、实现一个 i18n 框架
javascript·c#·.net
西西小飞龙1 小时前
Less/Sass Mixins vs. Extend
前端·less·sass
syjy21 小时前
(含下载)BeTheme WordPress主题使用教程
前端·wordpress·wordpress建站
Misnice1 小时前
shadcn如何使用
前端·reactjs
h_jQuery1 小时前
vue使用gm-crypto对数据进行sm4加密处理
前端·javascript·vue.js