项目需求:将表格数据中相同的数据背景色改为一致,效果大致如下
HTML代码:注意一定要加上,并使用table中的单元格的 style 的回调方法cell-style
<template slot-scope="scope">
<span>{{ scope.row.date.value }}</span>
</template>
<template>
<div class="about">
<el-table
:data="tableData"
border
style="width: 100%"
// 重点,使用这个回调方法
:cell-style="cellStyle"
>
<el-table-column prop="date" label="日期" width="180">
<template slot-scope="scope">
<span>{{ scope.row.date.value }}</span>
</template>
</el-table-column>
<el-table-column prop="name" label="姓名" width="180">
<template slot-scope="scope">
<span>{{ scope.row.name.value }}</span>
</template>
</el-table-column>
<el-table-column prop="address" label="地址">
<template slot-scope="scope">
<span>{{ scope.row.address.value }}</span>
</template>
</el-table-column>
</el-table>
</div>
</template>
再与后端协商数据格式如下:
<script>
export default {
data() {
return {
tableData: [
{
date: { value: "2016-05-02", state: 2 },
name: { value: "王虎", state: 0 },
address: { value: "上海市普陀区金沙江路 1517 弄", state: 2 },
},
{
name: { value: "王小虎", state: 2 },
date: { value: "2016-05-03", state: 1 },
address: { value: "上海区金沙江路 15市普陀16弄", state: 2 },
},
{
name: { value: "王虎", state: 0 },
date: { value: "2016-05-03", state: 1 },
address: { value: "上海区金沙江路 15市普陀18弄", state: 2 },
},
],
}
},
//方法如下
methods:{
cellStyle({ row, column, rowIndex, columnIndex }) {
let dataColor = false;
let nameColor = false;
Object.keys(row).forEach((key) => {
if (row[key].state == 1 && key == column.property) {
if (rowIndex === rowIndex && columnIndex === columnIndex) {
dataColor = true;
}
} else if (row[key].state == 0 && key == column.property) {
if (rowIndex === rowIndex && columnIndex === columnIndex) {
nameColor = true;
}
}
});
if (dataColor) {
return "backgroundColor:yellow";
}
if (nameColor) {
return "backgroundColor:pink";
}
},
}
}
</script>
设定表格单元格颜色,围绕style 的回调方法cell-style来进行就可以啦!!!