Vue——树行结构的el-table点击行高亮的问题

问题不大但很隐晦。这么小个问题最终花了几天才搞定,好几次想放弃,就一个感觉真的恶心。

场景一:直接修改el-table的样式。
修改插件的样式必须时全局的,但又不能影像到其他地方的el-table所以在前面加了父级div的classname.【程序员不需要你好牛逼但一定要规范,这样代码才容易维护,之前在大厂里经理交给我的】

.parent-box .el-table__body tr.current-row>td {//高亮点击的行
  background: rgb(77, 195, 255, 0.5) !important;
}
.parent-box .el-table__body tr:hover>td{//鼠标滑过时高亮行
  background: rgb(77, 195, 255, 0.2);
}

场景二:在点击后如果去页面没有元素被刷新,场景一是OK的。但如果有元素刷新(比如:显示隐藏某个div)会出现被点击高亮的行有马上恢复了原来的样子。
大概原因是:重新渲染列表,current-change发生了改变,冲原本选择的row,变成不在选择任何一行,导致问题很难排查。

网上看了很多人的都没说明白怎么处理,所以记录一下。

<template>
  <el-table
    ref="projectPlanTable"
    :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
    :row-key="(row)=>{return row.id}"
    highlight-current-row
    border
    default-expand-all 
    indent:10
    :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    class="project-plan-table"
    @row-click="funcProjectPlanRowClick"
    :row-style="rowClassRender"
    >
      <el-table-column prop="name" label="名称" width="120"></el-table-column>
      <el-table-column prop="type" label="分类" width="auto"></el-table-column>
    </el-table>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
      currentRowId: null,
    };
  },
  methods: {
    rowClassRender({row}) {
      if (row.id==this.currentRowId) {
        return { "background-color": "rgb(77, 195, 255, 0.5)" };
      } else {
        return '';
      }
    },
    funcProjectPlanRowClick(row){
      this.currentRowId = row.id;
    },
  }
};
</script>

<style lang="less" scoped>
.project-plan-table{
  width: 100%;
  height: 100%;
  color: #fff;
  font-size: 10px;
  border: 0;
}
</style>


几个地方:

  1. @row-click方法获取被点击行的id[这个id是自己的数据里面的,根据自己的数据换成自己的唯一标识就行]。
  2. :row-style在渲染每行的时候触发后面指定的方法。
  3. rowClassRender({row}){}方法的参数是 "{row}"话括弧不能少,否者无效。
  4. 不用setCurrentRow是因为setCurrentRow对于树状的table无效。

颜色渐变+点击高亮

rowClassRender({row, rowIndex}) {
  if (rowIndex%2 === 1) {
    if (row.id==this.currentRowId) {
      return { "background-color": "rgb(77, 195, 255, 0.5)" };
    }
    return { "background-color": "rgb(0, 0, 0, 0.5)" };
  }else{
    if (row.id==this.currentRowId) {
      return { "background-color": "rgb(77, 195, 255, 0.5)" };
    }
    return '';
  }
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值