The vue el-table table dynamically merges rows based on the acquired data

1. Requirements: Judging by the content of the first column of the table, if the values ​​are equal, these rows in the first column will be merged into the same row 2. Effect:
3.
insert image description here
Implementation method:
1. Set the span-method method for the table

<el-table
              :data="data"
              :span-method="objectSpanMethod"      //method
              style="width: 100%;"
              max-height="500"
              :row-style="{ height: '50px' }"
            >
              <el-table-column prop="datasetUrl" label="数据集" width="130"  >
              </el-table-column>
              <el-table-column prop="columnName" label="特征名称" >
              </el-table-column>

2. method
(1), process data, pass in the table array, and call when the array is obtained

getSpanArr(data) { 
    this.spanArr = []
      for (var i = 0; i < data.length; i++) {
            if (i === 0) {
                  this.spanArr.push(1);  //空数组,用来记录需要合并的行数
                  this.pos = 0  //标识
            } else {
              // 判断当前元素与上一个元素是否相同⬇️
        if (data[i].datasetUrl === data[i - 1].datasetUrl) {
                    this.spanArr[this.pos] += 1;
                    this.spanArr.push(0);    //相同则上一行合并数+1,本行合并数为0
                  } else {
                    this.spanArr.push(1);   //不相同则另起一行
                    this.pos = i;
                  }
            }
        }
    },

(2), the method of table binding, input the number of rows and columns, row and column identification, and perform the merge operation

objectSpanMethod({ row, column, rowIndex, columnIndex }) {
         
        if (columnIndex === 0) {    //如果是第一列
          const _row = this.spanArr[rowIndex];   //将每一行传入上述方法,获取到每一行的合并行数
            const _col = _row > 0 ? 1 : 0;
            return {
                  rowspan: _row,   //合并行
                  colspan: _col    //合并列
            }
        }
      },

3. Change the style according to the actual needs, and remember to use the vue style to penetrate when the element is not available.

Done ✅

Guess you like

Origin blog.csdn.net/buukyjmvni/article/details/120524004