【vue3+setup语法糖+element-plus】在表格中使用formatter格式化(语义化)数据显示

857 阅读1分钟

一、需求描述

image.png 如上图所示,从api接收到的类型状态是整型数据,但我们前端需要将其语义化,比如类型中的2要语义化成员工考核状态中的1要语义化成已完成,不然用户读不懂这些整数是啥意思。

二、解决办法

如果api接收到的数据可以直接显示,则使用prop属性即可,如下面考核标题一列。 但是类型状态需要语义化,除了使用prop属性之外,还需要使用:formatter属性,它调用一个函数,参数row: any传入当前行的所有数据,返回经过格式化处理的数据。

三、代码例子

:formatter="(row: any) => typeOptions[row.type - 1].label"的意思是根据row.type的数值索引typeOptionslabel值。

<template>
    <el-table :data="data" style="width: 100%">
        <el-table-column label="考核标题" prop="title" />
        <el-table-column label="类型" prop="type" :formatter="(row: any) => typeOptions[row.type - 1].label" />
        <el-table-column label="状态" prop="status" :formatter="(row: any) => StatusOptions[row.status - 1].label" />
    </el-table>
</template>

<script setup lang="ts">
const typeOptions = [
  {
    value: 1,
    label: '某a考核',
  },
  {
    value: 2,
    label: '员工考核',
  },
  {
    value: 3,
    label: '某b考核',
  },
]

const StatusOptions = [
  {
    value: 1,
    label: '已完成',
  },
  {
    value: 2,
    label: '未完成',
  },
]
</script>