element ui table 表格行颜色自定义。单元格颜色 。根据条件改变行或者单元格的颜色 电脑版发表于:2022/6/6 16:56 ### 行列样式主要是这几个 | 属性名 | 描述 | 回调函数 | | ------------ | ------------ | ------------ | | row-class-name | 行的 className 的回调方法,也可以使用字符串为所有行设置一个固定的 className。 | Function({row, rowIndex})/String | | row-style | 行的 style 的回调方法,也可以使用一个固定的 Object 为所有行设置一样的 Style。 | Function({row, rowIndex})/Object | | cell-class-name | 单元格的 className 的回调方法,也可以使用字符串为所有单元格设置一个固定的 className。 | Function({row, column, rowIndex, columnIndex})/String | | cell-style | 单元格的 style 的回调方法,也可以使用一个固定的 Object 为所有单元格设置一样的 Style。 | Function({row, column, rowIndex, columnIndex})/Object | ### 根据条件改变行的颜色 **如果是要设置每行的样式都一样可以这样绑定一个具体的值:row-style="rowStyle"** ``` <el-table height="666px" :data="courseRowdata" :header-cell-style="headerCellStyle" :row-style="rowStyle" ``` rowStyle直接在data中给固定的值: ``` data() { return { rowStyle: { color: '#fff', height: '39px', background: 'rgba(8, 65, 120, 0.4)', marginBottom: "10px", opacity: "0.8", paddingTop: "10px", paddingBottom: "10px", } } } ``` **根据条件改变某一行的颜色,就需要提供一个方法来返回需要的样式了** ``` <el-table height="666px" :data="teacherRowdata" :header-cell-style="headerCellStyle" :row-style="styleRowStyle" ``` 其中styleRowStyle是一个方法 ``` methods: { styleRowStyle(row) { console.log(row) let rowIndex = row.rowIndex // 默认的行样式 let rowStyle = { color: '#fff', height: '39px', background: 'rgba(8, 65, 120, 0.4)', marginBottom: "10px", opacity: "0.8", paddingTop: "10px", paddingBottom: "10px", } // 排名前三的变绿 if (rowIndex < 3) { rowStyle.background = "green" } // 排名后三不达标的就变红 let teacherDataCount = this.teacherRowdata.length if(rowIndex>=teacherDataCount - 3) { if(row.row.zh_number < 0.8) { rowStyle.background = "#ff5555" } } return rowStyle } } ``` 实现了一个简单的前三行变绿,后三行变红,效果如下: ![](https://img.tnblog.net/arcimg/aojiancc2/76a0778a357c45f385ce37c73fbdd676.png) ### 根据条件改变某一单元格的颜色 和改变行颜色逻辑是一样的,参考代码如下: ``` <el-table :data="rowData" border size="mini" :cell-style="styleBack"> <el-table-column label="row1">11111</el-table-column> <el-table-column property="" label="row2">22222</el-table-column> <el-table-column property="" label="row3">33333</el-table-column> <el-table-column property="" label="row3">44444</el-table-column> <el-table-column property="" label="row3">55555</el-table-column> <el-table-column property="" label="row3">66666</el-table-column> </el-table> ``` 数据: ``` rowData: [ { id: 1, num: 2 }, { id: 2, num: 3 }, { id: 3, num: 4 }, ], ``` 处理方法: ``` styleBack({ row, column, rowIndex, columnIndex }) { if (columnIndex == 1 && row.num > 3) { return { backgroundColor: "#0c87ef" }; }else if(columnIndex == 1){ return { backgroundColor: "#FDD56A" }; } } ```