一、处于某种原因,有时候一个表格里很多种样式,比如单元格动态改变字体颜色
如UI图
html:
通过:cell-style="cellStyle" 方法返回一个回调,具体参数看文档
<el-table
:data="tableData"
style="width: 100%"
:header-cell-style="{color: '#848484', fontSize: '14px'}"
:cell-style="cellStyle"
:default-sort = "{prop: 'date', order: 'descending'}"
>
</el-table>
js:
// 表体字体颜色设置
/***
* row为某一行的除操作外的全部数据
* column为某一列的属性
* rowIndex为某一行(从0开始数起)
* columnIndex为某一列(从0开始数起)
*/
cellStyle ({ row, column, rowIndex, columnIndex }) {
// 状态列字体颜色
if (row.status === '已发布' && columnIndex === 3) {
return 'color: #0CB618'
} else if (row.status === '暂不发布' && columnIndex === 3) {
return 'color: #EA1B29'
} else {
return 'color: #1a1a1b'
}
},
最后效果如下:
二、如果数据更复杂,或者表格的布局不一致,可以改变逻辑方法
UI图
后台返回的数据如下:
动态改变的单元格的数据在里面一层的数组里 ResultStr, 贴代码:
<el-table-column
prop="ProjectName"
label="项目名称"
width="100">
</el-table-column>
<el-table-column
:label="item.DateStr"
:prop="item.DateStr"
min-width='100'
v-for="(item, index) in tableHeader"
:key="index">
<el-table-column
label="结果"
width="80"
>
<span class="resColor" v-if="item.ResultStr === 'OK'">{{item.ResultStr}}</span>
<span class="badColor" v-else>{{item.ResultStr}}</span>
</el-table-column>
<el-table-column
label="图片"
width="80">
<span
class="lookImg"
@click="handleEdit(item.ImgPath)">查看</span>
</el-table-column>
直接使用数据判断在行内判断就行了,如图:
这种数据结构踩了第一种方法的坑:
一种:(forEach 不支持return和break,无论如何都会遍历完,所以后面只返回最后一个数据的值)
cellStyle ({ row, column, rowIndex, columnIndex }) {
// 状态列字体颜色
let resList = row.ResultList
// row.ResultList 为一行数据中的ResultList数组 ,column.label为所有列的对应表头子
resList.forEach((item, index) => {
if ((item.ResultStr === 'NG') && (column.label === '结果')) {
console.log('NG了')
return 'color: #fb7a7a'
} else {
return 'color: #000'
}
})
},
第二种:(for循环遇到return直接终止循环,所以只拿到了第一个进入的值)
cellStyle ({ row, column, rowIndex, columnIndex }) {
// 状态列字体颜色
let resList = row.ResultList
console.log(resList)
for (let i = 0; i < resList.length; i++) { // 编程式
console.log(resList[i].ResultStr)
if (resList[i].ResultStr === 'NG') {
console.log('NG进来了')
continue 'color: #fb7a7a'
} else {
return 'color: #000'
}
}
},
后面朋友提了两句,把方法放到html中去让它一致调用,就是使用filter过滤器,在过滤器函数中return(有时间我去尝试了再告诉小伙伴们,哈哈哈)
多少次跌跌撞撞才学会坚强,
多少次在迷茫之中寻找方向,
多少次跌倒之后再站起来面对!
版权声明:本文为agua001原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。