elementui rowstyle
修改 ElementUI 表格行样式
ElementUI 的表格组件允许通过 row-style 属性自定义行的样式。该属性可以接收一个函数,函数返回的对象会被应用到行的 style 属性中。
基本用法
在表格组件上绑定 row-style 属性,传入一个函数。该函数接收当前行数据 row 和行索引 rowIndex 作为参数,返回一个样式对象。
<el-table
:data="tableData"
:row-style="rowStyle">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
methods: {
rowStyle({ row, rowIndex }) {
return {
backgroundColor: rowIndex % 2 === 0 ? '#f9f9f9' : '#fff',
color: row.age > 30 ? 'red' : 'inherit'
}
}
}
条件样式
可以根据行数据动态设置样式。例如,当年龄大于 30 时,文字显示为红色:
rowStyle({ row }) {
return {
color: row.age > 30 ? 'red' : 'inherit'
}
}
斑马纹效果
通过判断行索引的奇偶性来设置交替的背景色:
rowStyle({ rowIndex }) {
return {
backgroundColor: rowIndex % 2 === 0 ? '#f5f5f5' : '#ffffff'
}
}
禁用行样式
对于某些特定行,可以添加禁用样式:
rowStyle({ row }) {
return row.disabled ? {
backgroundColor: '#eee',
color: '#ccc',
cursor: 'not-allowed'
} : {}
}
响应式样式
如果需要根据屏幕宽度调整行样式,可以在函数中加入媒体查询逻辑:
rowStyle({ row }) {
const style = {}
if (window.innerWidth < 768) {
style.fontSize = '12px'
}
return style
}
注意事项
- 样式对象中的属性需要使用驼峰命名法(如
backgroundColor而非background-color) - 返回的样式会直接应用到行的
style属性,优先级高于 CSS 样式表 - 对于复杂的样式逻辑,建议在计算属性或方法中预先处理好
通过灵活使用 row-style 属性,可以实现各种复杂的表格行样式需求。







