1. 使用 row-class-name 属性
这种方式可以为整行设置样式类:
<template>
<el-table
:data="tableData"
:row-class-name="tableRowClassName">
<!-- 表格列定义 -->
</el-table>
</template>
<script>
export default {
methods: {
tableRowClassName({row, rowIndex}) {
if (rowIndex === 1) {
return 'warning-row'
} else if (rowIndex === 3) {
return 'success-row'
}
return ''
}
}
}
</script>
<style>
.el-table .warning-row {
background-color: #fdf5e6;
}
.el-table .success-row {
background-color: #f0f9eb;
}
</style>
2. 使用 cell-class-name 属性
这种方式可以为单个单元格设置样式类:
<template>
<el-table
:data="tableData"
:cell-class-name="cellClassName">
<!-- 表格列定义 -->
</el-table>
</template>
<script>
export default {
methods: {
cellClassName({row, column, rowIndex, columnIndex}) {
if (columnIndex === 1 && row.status === 'error') {
return 'error-cell'
}
return ''
}
}
}
</script>
<style>
.el-table .error-cell {
background-color: #ffebeb;
}
</style>
3. 使用行内样式
通过 :cell-style
属性直接设置样式:
<template>
<el-table
:data="tableData"
:cell-style="cellStyle">
<!-- 表格列定义 -->
</el-table>
</template>
<script>
export default {
methods: {
cellStyle({row, column, rowIndex, columnIndex}) {
if (row.amount < 0) {
return {
backgroundColor: '#ffebeb',
color: '#ff4949'
}
}
return {}
}
}
}
</script>
4. 使用作用域插槽自定义样式
在需要更灵活的样式控制时,可以使用作用域插槽:
<template>
<el-table :data="tableData">
<el-table-column prop="status" label="状态">
<template #default="scope">
<div :style="{
backgroundColor: scope.row.status === 'success' ? '#f0f9eb' : '#ffebeb',
padding: '8px'
}">
{{ scope.row.status }}
</div>
</template>
</el-table-column>
</el-table>
</template>
5. 使用 header-cell-style 设置表头样式
<template>
<el-table
:data="tableData"
:header-cell-style="headerStyle">
<!-- 表格列定义 -->
</el-table>
</template>
<script>
export default {
methods: {
headerStyle() {
return {
backgroundColor: '#f5f7fa',
color: '#606266'
}
}
}
}
</script>
注意事项
- 使用
row-class-name
和cell-class-name
时,需要注意样式优先级问题 - 行内样式的优先级最高,但代码可维护性较差
- 使用作用域插槽自定义样式最灵活,但会带来一定的性能开销
- 建议根据具体场景选择合适的方案,简单场景使用类名方式,复杂场景考虑作用域插槽
以上就是在 Element UI 的 Table 组件中定义单元格底色的几种常用方式,每种方式都有其适用场景,开发时可以根据实际需求选择最合适的方案。