el-table 设置一列的颜色

在Vue项目的el-table组件中,设置某一列颜色可通过template动态控制class,实现数据颜色变化。针对直接写死column和大量列通过循环生成的情况,核心在于根据条件为单元格添加不同的class。示例代码分别展示了简单情况和复杂情况(涉及多重循环及在column数组中定义判断条件)的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

el-table 设置一列的颜色

在日常使用 el-table 中 有两种形式 一种是直接写死 column 另一种是大量的列 通过for循环遍历出来的

两种方法无论哪一种 其实核心思想都是 通过 template 控制不同的class 将对应的样式渲染出来 从而实现数据的颜色的转变 核心为class

直接上代码

第一种简单情况
在这里插入图片描述

   <el-table-column align="center" label="同比">
        <template slot-scope="scope">
          <span :class="scope.row.ordAvgYearly < 0 ? 'font-class-red' : 'font-class-green'">{{
            scope.row.ordAvgYearly
          }}</span>
        </template>
      </el-table-column>
       .font-class-red {

第二种情况 多重循环column复杂情况
在这里插入图片描述

<el-table-column
    v-for="column in columnsLeft"
    :key="column.key"
    :min-width="column.minWidth"
    :prop="column.key"
    :label="column.label"
    :width="column.width"
  >
	      <el-table-column
	        v-for="col in column.children"
	        :key="col.key"
	        :prop="col.key"
	        :label="col.label"
	        :width="col.width"
	      >
	        <template slot-scope="scope">
	          <span
	            :class="col.color ? scope.row[col.key] < 0 ? 'font-class-red' : 'font-class-green': ''"
	          >{{ scope.row[col.key] }}</span>
	        </template>
	      </el-table-column>
  </el-table-column>


data() {
return {
	columns: [
        {
          label: '终端揽件成本(元)',
          minWidth: '100',
          children: [
            { key: 'collCost', label: '成本金额' },
            { key: 'collAvgCost', label: '单均成本' },
            { key: 'collAvgYearly', label: '同比', color: true },
            { key: 'collAvgMonthly', label: '环比', color: true }
          ]
        },
        {
          label: '接货仓成本(元)',
          minWidth: '100',
          children: [
            { key: 'jhcCost', label: '成本金额' },
            { key: 'jhcAvgCost', label: '单均成本' },
            { key: 'jhcAvgYearly', label: '同比' },
            { key: 'jhcAvgMonthly', label: '环比' },
            { key: 'jhcPackageAvgCost', label: '接货仓包裹均成本金额' },
            { key: 'jhcPackageAvgYearly', label: '同比', color: true },
            { key: 'jhcPackageAvgMonthly', label: '环比', color: true }
          ]
        },
}
}
 .font-class-red {
    color: red !important;
  }
  .font-class-green {
    color: green !important;
  }
  .font-class-yellow {
    color:yellow !important;
  }

第二种情况复杂的原因是需要展示颜色的判断条件在column的数组中, 而不在数据里面 所以需要 class里面作两个判断

<template slot-scope="scope">
    <span
       :class="col.color ? scope.row[col.key] < 0 ? 'font-class-red' : 'font-class-green': ''"
     >{{ scope.row[col.key] }}</span>
 </template>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值