当前位置: 首页 > news >正文

vue3 el-table 行字体颜色 根据字段改变

在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推荐的现代写法。

http://www.lqws.cn/news/476119.html

相关文章:

  • Flink SourceFunction深度解析:数据输入的起点与奥秘
  • Flink作业三种部署模式:架构、配置与实战应用
  • C++主要知识点详解(引用,内联函数)
  • webpack+vite前端构建工具 - 8 代码分割
  • 生成器函数概念与用法详解
  • 【Clickhouse系列】增删改查:对比mysql
  • Clickhouse官方文档学习笔记
  • FastAPI 入门教程 #06:FastAPI 请求体和数据模型
  • 从零理解鱼眼相机的标定与矫正(含 OpenCV 代码与原理讲解)
  • PostgreSQL全栈部署指南:从零构建企业级高可用数据库集群
  • React Next快速搭建前后端全栈项目并部署至Vercel
  • 《DeepSeek原生应用与智能体开发实践》案例重现
  • 关于数学函数和数据类型扩展的详细讲解(从属GESP二级)
  • 30天pytorch从入门到熟练(day1)
  • Mybatis-Plus支持多种数据库
  • 【机器学习四大核心任务类型详解】分类、回归、聚类、降维智能决策指南
  • 多项目预算如何集中管控与动态调整
  • 将Linux装进口袋: Ubuntu to Go 制作
  • 【Linux】进程间多种通信方式对比
  • Typescript基础
  • 【后端】负载均衡
  • MiniMax-M1 开源,Kimi 深度研究内测,GPT-5 今夏发布,Gemini 2.5 稳定上线!| AI Weekly 6.16-22
  • 大模型MetaGPT面试题汇总及参考答案
  • Python-break、continue与else语句
  • OJ搭建:Judge0服务器、DeepSeek服务接入简介
  • 70、爬楼梯
  • 相机camera开发之差异对比核查四:测试机和对比机的Camera动态参数差异对比及关键字
  • 笨方法学python-习题1
  • 设计模式精讲 Day 10:外观模式(Facade Pattern)
  • 无锡哲讯科技:助力纺织业搭乘 SAP 数字化快车