实现 element-ui 的 el-table 单元格自定义样式
微wx笑
2022-03-14【前端开发】
5
0关键字:
element-ui el-table
有些时候我们需要根据条件,为特定的单元格指定自定义格式,以突出显示,element-ui 的 el-table 要怎么实现呢?
根据官方文档,我们需要使用:cell-style 单元格的 style 的回调方法,也可以使用一个固定的 Object 为所有单元格设置一样的 Style。 Function({row, column, rowIndex, columnIndex})/Object

相关代码:
el-table 添加 :cell-style="handleCellStyle" 单元格的 style 的回调方法
<el-table
:data="tableData"
stripe
border
style="width: 100%"
:header-cell-style="{background:'#70b6ff',color:'#FFF',fontSize:'16px'}"
:cell-style="handleCellStyle">
<el-table-column
prop="name"
label="参赛人员">
</el-table-column>
<el-table-column
prop="my_stock"
label="自选股">
</el-table-column>
<el-table-column
prop="work_stock"
label="作业股">
</el-table-column>
<el-table-column
prop="work_date"
label="作业股发布时间">
</el-table-column>
<el-table-column
prop="work_author"
label="作业股作者">
</el-table-column>
</el-table>
methods 中添加处理程序 handleCellStyle,注意参数的写法,是需要带花括号的!
如果你不想使用花括号的形式,那么只需要指定一个参数,比如:handleCellStyle(cell),那么cell的属性就有 row, column, rowIndex, columnIndex
methods: {
handleCellStyle({row, column, rowIndex, columnIndex}){
//console.log("handleCellStyle");
//console.log(row, column, rowIndex, columnIndex);
if (columnIndex == 1 || columnIndex == 2){
//console.log(cell.row);
var count = 0;
for(var i=0; i<this.tableData.length; i++){
dr = this.tableData[i];
if (columnIndex == 1 && (dr.my_stock == row.my_stock || dr.work_stock == row.my_stock)){
count++;
}
if (columnIndex == 2 && (dr.work_stock == row.work_stock || dr.my_stock == row.work_stock)){
count++;
}
}
if (count == 2){
return "color:white;background:#194a6e; font-weight: bold; font-size: 14px;";
}
if (count == 3){
return "color:red;background:#66bfbf; font-weight: bold; font-size: 14px;";
}
if (count > 3){
return "color:red;background:#00bfbf; font-weight: bold; font-size: 14px;";
}
}
}
}效果如下图:相同的股票会突出显示

本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/front/2022-03-14/1093.html



