el-table 设置行背景颜色 鼠标移入高亮问题处理

一、 设置行背景颜色

1. 需求描述

后端返回表格数据,有特定行数需要用颜色标识。类似于以下需求:

2. 解决方式

方式 区别
:row-class-name="tableRowClassName" 已返回类名的形式设置样式,代码整洁,但是会鼠标高亮,导致背景颜色失效
:cell-style="cellStyle" 以返回样式的形式设置,无鼠标高亮问题

2.1 表格代码

复制代码
<el-table
    :data="tableData"
    style="width: 100%"
    class="tableStyle"
    :row-class-name="tableRowClassName"
    :cell-style="cellStyle">
    <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>

2.2 :row-class-name="tableRowClassName" 方式

复制代码
/**
     * @description: 合计行处理:  :row-class-name="tableRowClassName" 方式
     * @param {*}row, rowIndex
     * @return {*}
     */
    tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      }

2.3 :cell-style="cellStyle"方式

复制代码
/**
     * @description: 合计行处理:   :cell-style="cellStyle"方式
     * @param {*}row, rowIndex
     * @return {*}
     */
    cellStyle({ row, rowIndex }) {
     if (rowIndex === 1) {
            return 'background: #4D939F !important;color: #fff;'
        } else if (rowIndex === 3) {
           return 'background: #e6a23c !important;color: #fff;'
        }
        return '';
      }

3. 样式设置

3.1 row-class-name方式的样式

复制代码
<style lang='scss' scoped>
/deep/ .el-table .warning-row td {
  background: #4D939F !important;
  color: #fff;
}

/deep/ .el-table .fixedRow td {
  background: #4D939F !important;
  color: #fff;
  position: sticky;
  bottom: 0;
  width: 100%;
}
<style>

4. 表头设置颜色

4.1 第一种直接设置

复制代码
<style>
.el-table th.red {
  background-color: #FBBFBC;
  color: #fff;
}

.el-table th.green {
  background-color: #FEDDB6;
  color: #fff;
}
</style>

4.2 第二种 设置类名 避免样式污染 推荐第二种

注意,是.tableStyle.el-table 不是.tableStyle .el-table

复制代码
<style>
.tableStyle.el-table th.red {
  background-color: #FBBFBC;
  color: #fff;
}

.tableStyle.el-table th.green {
  background-color: #FEDDB6;
  color: #fff;
}
</style>
相关推荐
我叫黑大帅1 小时前
Vue3和Uniapp的爱恨情仇:小白也能懂的跨端秘籍
前端·javascript·vue.js
None3212 小时前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js
Qinana2 小时前
从代码到智能体:MCP 协议如何重塑 AI Agent 的边界
前端·javascript·mcp
洋洋技术笔记3 小时前
Vue实例与数据绑定
前端·vue.js
Marshall1513 小时前
zzy-scroll-timer:一个跨框架的滚动定时器插件
前端·javascript
明月_清风4 小时前
打字机效果优化:用 requestAnimationFrame 缓冲高频文字更新
前端·javascript
明月_清风4 小时前
Markdown 预解析:别等全文完了再渲染,如何流式增量渲染代码块和公式?
前端·javascript
牛奶13 小时前
Vue 基础理论 & API 使用
前端·vue.js·面试
牛奶13 小时前
Vue 底层原理 & 新特性
前端·vue.js·面试
pe7er14 小时前
状态提升:前端开发中的状态管理的设计思想
前端·vue.js·react.js