在 Element UI 的?el-table
?組件中,cell-class-name
?屬性用于動態自定義表格單元格的 CSS 類名,通常用于根據數據條件設置樣式。
1. 基本用法
在?el-table
?上綁定?:cell-class-name
?屬性,值為一個函數。該函數接收一個對象參數,返回字符串(類名)或數組(多個類名)。
<el-table :data="tableData" :cell-class-name="cellClassName"
><el-table-column prop="name" label="姓名"></el-table-column><el-table-column prop="age" label="年齡"></el-table-column>
</el-table>
2. 函數參數說明
函數格式:({ row, column, rowIndex, columnIndex }) => className
row: 當前行數據
column: 當前列配置
rowIndex: 行索引(從 0 開始)
columnIndex: 列索引(從 0 開始)
3. 示例代碼
根據數據條件添加類名
methods: {cellClassName({ row, column, rowIndex, columnIndex }) {// 針對特定列設置樣式if (column.property === 'age') {if (row.age > 60) {return 'warning-cell'; // 年齡大于60添加警告樣式}}// 針對特定行設置樣式if (rowIndex === 0) {return 'first-row-cell'; // 第一行特殊樣式}// 默認返回空return '';}
}
CSS 定義樣式
.warning-cell {background-color: #fff6f7;color: #ff0000;font-weight: bold;
}.first-row-cell {background-color: #f5f7fa;
}
4. 高級用法
返回多個類名
cellClassName({ row, column }) {const classes = [];if (row.status === 'error') {classes.push('error-cell');}if (column.property === 'name') {classes.push('bold-cell');}return classes; // 返回數組,如 ['error-cell', 'bold-cell']
}
結合列屬性判斷
cellClassName({ column }) {// 為表頭是"操作"的列設置樣式if (column.label === '操作') {return 'action-cell';}
}
5. 注意事項
優先級問題:自定義類名會覆蓋 Element 默認樣式,必要時使用?
!important
。性能優化:避免在函數中執行復雜計算,特別是大數據表格。
列標識:建議通過?
column.property
(對應?prop
?值)或?column.label
?識別列。
完整示例
<template><el-table :data="tableData" :cell-class-name="cellClassName"><el-table-column prop="name" label="姓名"></el-table-column><el-table-column prop="age" label="年齡"></el-table-column><el-table-column prop="status" label="狀態"></el-table-column></el-table>
</template><script>
export default {data() {return {tableData: [{ name: '張三', age: 25, status: '正常' },{ name: '李四', age: 70, status: '警告' }]};},methods: {cellClassName({ row, column }) {// 年齡列且值大于60if (column.property === 'age' && row.age > 60) {return 'warning-cell';}// 狀態列為"警告"if (column.property === 'status' && row.status === '警告') {return 'error-cell';}}}
};
</script><style>
.warning-cell {background: #fff8e6;color: #ff9900;
}
.error-cell {color: #ff0000;font-weight: bold;
}
</style>