el-table单元格背景色动态改变

首先在el-table加上这个 :cell-style=“tableCellStyle”

<el-table :data="turnoutList" border :height="300" :cell-style="tableCellStyle">
	<el-table-column label="设备名称" width="110px" align="center" key="devName" prop="devName" fixed
                         sortable :show-overflow-tooltip="true">
        </el-table-column>
 </el-table>

然后是js方法

<script setup>
//这里是需要动态改变背景色的单元格,键是label,值是prop
const fieldMappings = {
  '设备名称': 'devName',
  '灯光配置': 'lightNum',
};

//动态改变单元格背景色
function tableCellStyle({ row, column, rowIndex, columnIndex }) {
  const fieldLabel = column.label;
  const fieldName = fieldMappings[fieldLabel];

  if (fieldName && (row[fieldName] === undefined || row[fieldName] === '')) {
    return { 'background-color': 'red' };
  }
}
</script>

效果如下,第一行有值,第二行没值背景色为红色
在这里插入图片描述

Vue3中,如果你想要给`el-table`组件的单元格添加背景颜色,你可以通过`cell-class-name`属性或者直接在模板中使用`v-bind:class`指令来动态设置。以下是两种常见的方式: **1. 使用`cell-class-name`属性** 在`el-table-column`标签中,你可以设置`cell-class-name`属性,然后在对应的值里返回一个计算函数,这个函数会接收当前行的数据作为参数,并根据数据的某个字段的值来决定背景色。 ```html <template> <el-table-column prop="yourDataField" label="列名" cell-class-name="getClassByData" /> </template> <script> export default { methods: { getClassByData(row) { // 根据row.yourDataField的值来决定背景色 if (row.yourDataField === '条件1') { return 'bg-color-1'; } else if (row.yourDataField === '条件2') { return 'bg-color-2'; } // 如果没有特定匹配,可以返回默认颜色或者其他默认处理 return 'default-bg-color'; }, }, }; </script> ``` **2. 使用`v-bind:class`指令** 在每个单元格的模板上,你可以直接使用`v-bind:class`绑定一个对象,对象的键对应预设的颜色类名,值是一个计算属性,根据实际数据决定应该显示哪种颜色。 ```html <template> <el-table-cell v-for="(item, index) in yourData" :key="index"> <span :class="{ backgroundColor: determineColor(item) }">{{ item.label }}</span> </el-table-cell> </template> <script> export default { methods: { determineColor(item) { // 根据item的值判断并返回颜色类名 if (item.field === '值1') { return 'color-1'; } else if (item.field === '值2') { return 'color-2'; } return ''; }, }, }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值