基于 Vue3 和 Element Plus 的 <el-tag> 二次封装实现数字字典标签展示

360 阅读2分钟

在前端项目中,我们常常会接收到一些数字状态码(如 012 等),这些数字在业务语义上通常代表某种状态。为了让页面更直观、可读,我们往往需要将这些数字转换成对应的“标签”文字,并配以颜色样式显示出来,这也就是数字字典组件的使用场景。

本文将基于 Vue3 + Element Plus,通过对 <el-tag> 的二次封装,完成一个支持数字字典的状态标签组件(仅前端部分)。

1、定义 dictType 类型结构

我们首先定义 el-tag 所支持的所有配置项,便于后续统一控制:

interface dictType {
  label: string;
  value: number | null;
  type: 'primary' | 'success' | 'info' | 'warning' | 'danger';
  closable: boolean;
  hit: boolean;
  color: string;
  size: 'large' | 'default' | 'small';
  effect: 'dark' | 'light' | 'plain';
  round: boolean;
}

2、创建组件并设置默认值

接着我们使用 reactive 定义组件的默认属性:

const defaultData = reactive<dictType>({
  label: '',
  value: null,
  type: 'primary',
  closable: false,
  hit: false,
  color: '',
  size: 'default',
  effect: 'light',
  round: false
});

3、模拟字典数据并匹配值

实际开发中,data 通常来自后端接口,这里使用模拟数据进行演示:

const data = [
  { label: '使用中', value: 2, type: 'primary' },
  { label: '空闲中', value: 3, type: 'success' },
  { label: '维护中', value: 4, type: 'warning' },
  { label: '待维修', value: 5, type: 'danger' }
];

为组件传入的 value 设置 props,且为必传项:

const props = defineProps({
  value: {
    type: Number,
    required: true
  }
});

这里的写法也可以为


const props = defineProps({
    value: Number
})

接着定义匹配函数(此处用模拟数据):

const getDict = () => {
  const item = data.find((item) => item.value === props.value);
  if (item) Object.assign(defaultData, item);
};

使用 Object.assign() 可保留响应式,批量更新字段。

onMounted() 中执行一次:

onMounted(() => {
  getDict();
});

组件模板部分

<template>
  <el-tag
    :type="defaultData.type"
    :closable="defaultData.closable"
    :hit="defaultData.hit"
    :color="defaultData.color"
    :size="defaultData.size"
    :effect="defaultData.effect"
    :round="defaultData.round"
  >
    {{ defaultData.label }}
  </el-tag>
</template>

使用方式示例

<DictTag :value="scope.row.status" />

效果展示

image.png

欢迎大家留言探讨你们的实践经验,如有疏漏或不妥之处,欢迎在评论区指出,互相学习,共同进步!