在Vue 3中使用Element Plus的<el-table>
组件时,如果你想根据某个字段的值改变行的字体颜色,可以通过自定义渲染单元格(cell)的方式来实现。这可以通过使用<el-table-column>
的render
属性或者使用scoped-slots
来实现。下面我会展示两种方法:
方法1:使用render
函数
你可以在<el-table-column>
中使用render
函数来定义如何渲染单元格,从而根据字段值改变字体颜色。
<template>
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="status" label="状态">
<template #default="scope">
<span :style="{ color: getColor(scope.row.status) }">{{ scope.row.status }}</span>
</template>
</el-table-column>
</el-table>
</template>
<script setup>
import { ref } from 'vue';
const tableData = ref([
{ name: '张三', status: '正常' },
{ name: '李四', status: '警告' },
{ name: '王五', status: '危险' }
]);
function getColor(status) {
switch (status) {
case '正常':
return 'green';
case '警告':
return 'orange';
case '危险':
return 'red';
default:
return 'black';
}
}
</script>
方法2:使用scoped-slots
(旧版语法)
如果你使用的是Vue 2或者旧的Element UI版本,可能会用到scoped-slots
。但在Vue 3和Element Plus中,推荐使用render
函数或者Vue 3的<template #default>
语法。不过,为了完整性,这里也展示如何使用scoped-slots
:
<template>
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="status" label="状态" width="180">
<template #default="scope">
<span :style="{ color: getColor(scope.row.status) }">{{ scope.row.status }}</span>
</template>
</el-table-column>
</el-table>
</template>
<script setup>
import { ref } from 'vue';
const tableData = ref([
{ name: '张三', status: '正常' },
{ name: '李四', status: '警告' },
{ name: '王五', status: '危险' }
]);
function getColor(status) {
switch (status) {
case '正常':
return 'green';
case '警告':
return 'orange';
case '危险':
return 'red';
default:
return 'black';
}
}
</script>
注意:在Vue 3中,推荐使用render
函数或者Vue 3的<template #default>
语法,因为它们提供了更好的类型支持和更现代的模板功能。上面的两种方法都可以工作,但第一种方法(使用render
函数)是Vue 3推荐的现代写法。