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>