element table组件合并单元格

576 阅读1分钟

合并单元格,如果situation 一致,则合并

getSpanArr(data)方法 data就是我们从后台拿到的数据,通常是一个数组;spanArr是一个空的数组,用于存放每一行记录的合并数;pos是spanArr的索引。如果是第一条记录(索引为0),向数组中加入1,并设置索引位置;如果不是第一条记录,则判断它与前一条记录是否相等,如果相等,则向spanArr中添入元素0,并将前一位元素+1,表示合并行数+1,以此往复,得到所有行的合并数,0 即表示该行不显示

mounted () {
    this.getSpanArr(this.tableData)
},
methods: {
    getSpanArr(data) {
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
        } else {
            // 判断当前元素与上一个元素是否相同
            if (data[i].situation === data[i - 1].situation) {
                this.spanArr[this.pos] += 1;
                this.spanArr.push(0);
            } else {
                this.spanArr.push(1);
                this.pos = i;
            }
        }
    }
},
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        // alert(_row);
        // alert(_col);
        console.log('row--', _row)
        console.log('col--', _col)
        return {
            rowspan: _row,
            colspan: _col
        };
    }
}

结果