解决el-table中tree-props的嵌套表格展示添加背景色展开与收缩子表格动态添加背景色

171 阅读1分钟

效果图:

Snipaste_2024-05-14_17-58-41.png

1.使用 @expand-change="expandChange" 绑定事件;

2.使用:row-style="rowClassName" 设置样式;

3.在mounted中调用,页面一加载就给子表格添加背景色;(这一步也可以在第二点中进行设置添加);

    addStyleToFirstLevelRows() {
      // 获取第一级行元素
      const firstLevelRows = this.$refs.table.$el.querySelectorAll('.el-table__row--level-1');

      // 为每个第一级行添加样式
      firstLevelRows.forEach(row => {
        row.style.backgroundColor = 'pink';
      });
      // debugger;
    },

4.定义个数组来接收,在expandChange事件中把id添加到数组


    expandChange(row, expandedRows) {
      if (expandedRows) {
        // 如果有行展开,将该行的id添加到highlightRows数组中
        this.highlightRows.push(row.id);
      } else {
        // 如果没有行展开,从highlightRows数组中移除该行的id
        this.highlightRows = this.highlightRows.filter(id => id !== row.id);
      }
    },

5.在第二步中设置样式 rowClassName({ row, rowIndex }) {

  // 如果行的id在highlightRows数组中,就添加样式
  if (this.highlightRows.includes(row.id)) {
    return {
      "background-color": "pink",
    }
  }
  }