el-table后端接口返回数字,前端转换成文字渲染表格

在工作中,经常后端接口返回的某些字段是数字,需要前端做一下处理,把每个数字对应的文字渲染到表格中。本篇文章就是学习如何实现该功能的:
博主「阿林阿林」的原创文章
原文链接:https://blog.csdn.net/qq_41793354/article/details/121636702

以下是对后端返回的字段没有做处理直接渲染的结果,可以看到我们需要的操作详情字段是一个数字,但是我们需要将它变成文字展示表格中

在这里插入图片描述
下面直接上代码
template:

<el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="operTime" label="操作时间" />
        <el-table-column prop="accountName" label="用户名" />
        <el-table-column prop="operName" label="姓名" />
        <el-table-column prop="operModule" label="操作模块" />
        <el-table-column prop="businessType" label="操作详情">
          <template #default="scope"> 
            {
    
    {
    
    getLabel(operDetails, scope.row.businessType, 'businessType', 'businessLabel')}}
          </template>
        </el-table-column>
      </el-table>

js:

// 操作详情的编号
    const operDetails = [
      {
    
    businessType: 0,businessLabel: '其他' },
      {
    
    businessType: 1,businessLabel: '新增'},
      {
    
    businessType: 2,businessLabel: '修改'},
      {
    
    businessType: 3,businessLabel: '删除'},
      {
    
    businessType: 4,businessLabel: '查看' }
    ]
    /**
      * 根据传入的值,返回对应的中文name,常用的地方是表格
      * list: 传入的源数组
      * id: 传入的值
      * value: 源数组中为了匹配id值的字段名称
      * label: 源数组中需要返回显示中文的字段名称
      * 示例:arr:[{businessType: 0,businessLabel:'其他'},{businessType: 1,businessLabel:'新增'}]
      * 调用getLabel(arr, 1, "businessType", "businessLabel")返回 新增
      *  */
    //  根据后端返回的数字编码,显示相应的文字
     const getLabel=(list, id, value, label)=> {
    
    
      if (id != '' && Array.isArray(list) && list.length != 0) {
    
    
        return !list.find(item => item[value] == id) ? id : list.find(item => item[value] == id)[label]
      } else {
    
    
        return id
      }
    }

最终效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_56733569/article/details/129689736