ant-design-vue和element-ui中的表格合合并相同行的方法

4,462 阅读1分钟

ant-design-vue

  • 设置表格列属性的自定义属性
customRender: (value, row, index) => {
                const obj = {
                  children: value,
                  attrs: {}
                };
                obj.attrs.rowSpan = this.myArray[index];
                return obj;
              }
  • 定义合并单元格方法
 func(data) {
      //保存上一个name
      var x = "";
      //相同name出现的次数
      var count = 0;
      //该name第一次出现的位置
      var startindex = 0;

      for (var i = 0; i < data.length; i++) {
        //根据学校id进行合并
        var val = data[i].schoolId;
        if (i == 0) {
          x = val;
          count = 1;
          this.myArray[0] = 1; // []
        } else {
          if (val == x) {
            count++;
            this.myArray[startindex] = count;
            this.myArray[i] = 0;
          } else {
            count = 1;
            x = val;
            startindex = i;
            this.myArray[i] = 1;
          }
        }
      }
    }
  • 调用合并单元格的方法
    this.myArray = new Array(this.tableData.length);
    this.func(this.tableData);

element-ui

  • el-table设置属性 span-method="objectSpanMethod
  • 合并行方法
    function objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
          // 第一列相同学校的单元格合并
          const _row = this.spanArr[0][rowIndex]
          return {
            rowspan: _row,
            colspan: 1
          }
        }
      }

  • 计算合并的行数
 rowspan (idx, prop) {
        this.spanArr[idx] = [] // []
        this.position = 0  // 0
        <!-- 要合并的表格数据 -->
        this.tableData.forEach((item, index) => {
          if (index === 0) {
            this.spanArr[idx].push(1)
            this.position = 0
          } else {
            if (
              this.tableData[index]['listenSchoolId'] ===
              this.tableData[index - 1]['listenSchoolId']
            ) {
              this.spanArr[idx][this.position] += 1 // 有相同项
              this.spanArr[idx].push(0) // 名称相同后往数组里面加一项0
            } else {
              this.spanArr[idx].push(1) // 同列的前后两行单元格不相同
              this.position = index
            }
          }
        })
      }