需求:
如果有多条id相同时,所在行展示颜色,并且重复id若是不一样,所在行颜色也要不一样。具体展示效果用时间列代替id。
实现思路:
因为考虑到列表中 oldArr
(原数组)重复id的排序并不是连续的,所以对id进行去重,并列出重复次数大于1的id数组 arr
。对列表数据重新处理,如果所在行的id等于arr里的某个id,那么就添加一个type属性,为展示颜色做准备。实现代码如下:
const idCounts = oldArr.reduce((acc, obj) => {
acc[obj.policeId] = (acc[obj.policeId] || 0) + 1;
return acc;
}, {});
// 找出重复的 id
const arr = Object.keys(idCounts).filter((key) => idCounts[key] > 1).map(Number);
console.log(arr, "arr");
oldArr.forEach((item, index) => {
if (arr.indexOf(item.policeId)) {
item.type = arr.indexOf(item.policeId);
}
});
行样式设置
对列表处理后,就可以根据添加的type属性设置行样式了。实现代码如下:
在 <el-table>
标签里添加 :row-class-name="tableRowClassName"
,在 methods
中添加方法:
methods: {
tableRowClassName({ row, rowIndex }) {
console.log(row.type, row.type % 3);
if (row.type % 3 == 0) {
return "yellow-row";
} else if (row.type % 3 == 1) {
return "blue-row";
} else if (row.type % 3 == 2) {
return "green-row";
} else {
return "";
}
},
}
设置相应的 css
样式
::v-deep .el-table .blue-row {
background: #daecfe;
}