Vue-ElementUI---Table组件使用-行合并

需求:按照数据的id进行行合并

15916729731.jpg

首先---查看文档

需要用到的api: 合并行或列的计算方法 Function({ row, column, rowIndex, columnIndex })

参数 说明 类型
span-method 合并行或列的计算方法 Function({ row, column, rowIndex, columnIndex })
cell-mouse-enter 当单元格 hover 进入时会触发该事件 row, column, cell, event
cell-mouse-leave 当单元格 hover 退出时会触发该事件 row, column, cell, event
row-class-name 行的 className 的回调方法,也可以使用字符串为所有行设置一个固定的 className。 Function({row, rowIndex})/String

行合并方法

这里根据数据的id是否相同进行合并,把相同id的数据对应的行号放到一个数组里面然后以id为key,行号数组为value进行存储

  private OrderIndexArr: { [key: string]: number[] } = {};

  private rowIndex = '-1';

  private hoverOrderArr: number[] = [];

  // 封装表格数据---按照某一列进行合并
  private getDatalistCaculate() {
    const orderObj: { [key: string]: number[] } = {};
    this.projectLists.forEach(
      (element: ProjectManageModule.ProjectInfo, index: number) => {
        const id = element.id || '';
        if (orderObj[id]) {
          orderObj[id].push(index);
        } else {
          orderObj[id] = [];
          orderObj[id].push(index);
        }
      }
    );
    this.OrderIndexArr = orderObj;
  }

  // 合并单元格
  objectSpanMethod({
    row,
    column,
    rowIndex,
    columnIndex
  }: {
    row: ProjectManageModule.ProjectInfo;
    column: { [key: string]: any };
    rowIndex: number;
    columnIndex: number;
  }) {
    if (columnIndex === 0) {
      // 如果当前行与上一行id这个字段一样
      if (rowIndex > 0 && row.id === this.projectLists[rowIndex - 1].id) {
        return {
          rowspan: 0,
          colspan: 0
        };
      } else {
        const id = row.id || '';
        const rows: number[] = this.OrderIndexArr[id];
        const length = rows.length;
        return {
          rowspan: length,
          colspan: 1
        };
      }
    }
  }

解决鼠标悬浮表格样式问题

当有超过两行数据合并后鼠标悬浮上去会发现不是合并的行处于active状态而是当读一行一行悬浮后才会处于active状态,这样看上去会非常别扭。这里api的处理逻辑就是鼠标进入事件判断当前行是否为合并行,如果是的话就把他的一起合并的行添加一个类名然后添加背景颜色。


  // 添加类名
  private rowClassName({
    row,
    rowIndex
  }: {
    row: ProjectManageModule.ProjectInfo;
    rowIndex: number;
  }) {
    const rows: number[] = this.hoverOrderArr;
    if (rows.includes(rowIndex)) {
      return 'success-row';
    }
  }

  // 鼠标悬浮行
  private cellMouseEnter(row: any, column: any, cell: any, event: any) {
    this.rowIndex = row.rowIndex + '';
    this.hoverOrderArr = [];
    for (const key in this.OrderIndexArr) {
      if (key === row.id) {
        this.hoverOrderArr = this.OrderIndexArr[row.id];
      }
    }
  }

  private cellMouseLeave(row: any, column: any, cell: any, event: any) {
    this.rowIndex = '-1';
  }

如果觉得文章还不错可以关注我的博客

你可能感兴趣的:(Vue-ElementUI---Table组件使用-行合并)