vue3 el-table 行颜色根据 字段改变
在 Vue 3 中使用 Element Plus 的 <el-table>
组件来根据某个字段改变行的颜色,可以通过自定义渲染函数或使用 row-class-name
属性来实现。以下是两种常见的方法:
方法 1:使用 row-class-name
属性
<el-table>
组件的 row-class-name
属性允许你根据行的数据动态返回一个类名,你可以在这个类名中定义颜色。
<template><el-table :data="tableData" row-class-name="rowClassName"><el-table-column prop="date" label="日期" width="180"></el-table-column><el-table-column prop="name" label="姓名" width="180"></el-table-column><el-table-column prop="address" label="地址"></el-table-column></el-table>
</template><script setup>
import { ref } from 'vue';const tableData = ref([{ date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄', type: 'A' },{ date: '2016-05-04', name: '张小刚', address: '上海市普陀区金沙江路 1517 弄', type: 'B' },// 更多数据...
]);const rowClassName = ({ row, rowIndex }) => {if (row.type === 'A') {return 'row-color-a';} else if (row.type === 'B') {return 'row-color-b';}return ''; // 默认返回空字符串,不应用任何特殊样式
};
</script><style>
.row-color-a {background-color: #f0f9eb; /* 例如,类型A的行背景色 */
}
.row-color-b {background-color: #ebf4fa; /* 例如,类型B的行背景色 */
}
</style>
方法 2:使用自定义渲染函数
如果你需要更复杂的行样式控制,可以使用 <el-table-column>
的 render
函数来自定义每一行的渲染。
<template><el-table :data="tableData"><el-table-column prop="date" label="日期" width="180"></el-table-column><el-table-column prop="name" label="姓名" width="180"></el-table-column><el-table-column prop="address" label="地址"></el-table-column><el-table-column label="操作" width="100"><template #default="{ row, rowIndex }"><div :class="getRowClass(row)">{{ row.type }}</div></template></el-table-column></el-table>
</template><script setup>
import { ref } from 'vue';const tableData = ref([{ date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄', type: 'A' },{ date: '2016-05-04', name: '张小刚', address: '上海市普陀区金沙江路 1517 弄', type: 'B' },// 更多数据...
]);const getRowClass = (row) => {if (row.type === 'A') {return 'row-color-a';} else if (row.type === 'B') {return 'row-color-b';}return ''; // 默认返回空字符串,不应用任何特殊样式
};
</script><style>
.row-color-a {background-color: #f0f9eb; /* 例如,类型A的行背景色 */
}
.row-color-b {background-color: #ebf4fa; /* 例如,类型B的行背景色 */
}
</style>
这两种方法都可以根据字段。