需求:一个table中,行头(表头)是自动生成,列头(第一列)也是自动生成,中间的数据按照 值的大小去显示不同的单元格背景色。
html
<el-table :data="tableData" :cell-style="tableCellStyle">
<el-table-column label="" width="50" fixed>
<template slot-scope="scope">
{{ scope.row.y}}
</template>
</el-table-column>
<el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop" :label="column.label" >
</el-table-column>
</el-table>
data中定义(假数据)
tableData: [
{y: -1, x1: null, x2: 0.12, x3: 0.31 , total: 1 },
{y: 0, x1: 0.2, x2: 0.123, x3: 0.32, total: 2 },
{y: 1, x1: 0.3, x2: 0.08, x3: 0.33, total: 3 }
],
tableColumns: [
{ prop: 'x1', label: '0' },
{ prop: 'x2', label: '1' },
{ prop: 'x3', label: '2' },
{ prop: 'total', label: '合计' }
],
methods
tableCellStyle({ row, column, rowIndex, columnIndex }) {
console.log('row', row, column, rowIndex, columnIndex, Object.keys(row)[columnIndex])
if (Object.keys(row)[columnIndex] !== 'y' && Object.keys(row)[columnIndex] !== 'total') {
let con = row[Object.keys(row)[columnIndex]]
console.log('con', con)
if(con == null) {
return '';
} else if (con < 0.1) {
return 'background-color: red;';
} else if (con>0.1 && con< 0.2) {
return 'background-color: yellow;';
} else {
return 'background-color: green;';
}
}