To change the background color in an Element UI table based on the content of the table data, you can use cell-style
properties and style functions.
First, you need to add an attribute in the column definition of the table cell-style
, which receives a function to return the corresponding style object according to the content of the cell.
Suppose your table data is as follows:
data() {
return {
tableData: [
{ nurseName: "Wang Wei", mondayStatus: "E", thursdayStatus: "E", wednesdayStatus: "E", thuesdayStatus: "E", fridayStatus: "E", saturdayStatus: "", sundayStatus: "", id: "1" },
{ nurseName: "Shi Yu", mondayStatus: "E", thursdayStatus: "E", wednesdayStatus: "E", thuesdayStatus: "E", fridayStatus: "E", saturdayStatus: "", sundayStatus: "", id: "2" },
{ nurseName: "Zhao XiaoDong", mondayStatus: "D2", thursdayStatus: "D2", wednesdayStatus: "D2", thuesdayStatus: "V", fridayStatus: "V", saturdayStatus: "", sundayStatus: "", id: "3" },
{ nurseName: "Luo Chris", mondayStatus: "D2", thursdayStatus: "D2", wednesdayStatus: "D2", thuesdayStatus: "D2", fridayStatus: "D2", saturdayStatus: "", sundayStatus: "", id: "4" },
]
}
}
Then, in the table's column definition, you can add cell-style
properties to set the background color of the cell, like this:
<el-table :data="tableData">
<el-table-column prop="nurseName" label="Nurse Name"></el-table-column>
<el-table-column prop="mondayStatus" label="Monday" :cell-style="statusCellStyle"></el-table-column>
<el-table-column prop="thursdayStatus" label="Thursday" :cell-style="statusCellStyle"></el-table-column>
<el-table-column prop="wednesdayStatus" label="Wednesday" :cell-style="statusCellStyle"></el-table-column>
<el-table-column prop="thuesdayStatus" label="Tuesday" :cell-style="statusCellStyle"></el-table-column>
<el-table-column prop="fridayStatus" label="Friday" :cell-style="statusCellStyle"></el-table-column>
<el-table-column prop="saturdayStatus" label="Saturday" :cell-style="statusCellStyle"></el-table-column>
<el-table-column prop="sundayStatus" label="Sunday" :cell-style="statusCellStyle"></el-table-column>
</el-table>
Next, you need to define the corresponding style function in the Vue instance, and return different style objects according to the content of the cell. For example:
methods: {
statusCellStyle({ row, column }) {
if (row[column.property] === "E") {
return { background: "green" };
} else if (row[column.property] === "D2") {
return { background: "yellow" };
} else if (row[column.property] === "V") {
return { background: "red" };
} else {
return { background: "white" };
}
}
}
With the above settings, the background color of each cell will change dynamically according to its content. You can modify the logic and color settings in the style function according to actual needs.
The effect is as shown below