vue elementui table合并单元格

112 阅读1分钟

首先data里定义2个变量

spanArr: [], // 用于存放需要合并的行的个数
spanIndex: 0, // 记录spanArr数组的下标

html里

// 表格
<el-table
   :data="nodesData"
   :span-method="objectSpanMethod"
   border
>

methods

        // 处理数据
        getSpanArr(data) {
            for (let i = 0; i < data.length; i++) {
                if (i === 0) {
                    this.spanArr.push(1);
                    this.spanIndex = 0;
                } else {
                    // 判断当前行与前一行内容是否相同
                    if (data[i].id=== data[i - 1].id) {
                        this.spanArr[this.spanIndex] += 1; // 相同的话,当前下标所代表的值加一,例如:第一列的前三行可合并
                        this.spanArr.push(0);// 记录完毕后,再往数组里添加一个元素0,作为下一次合并的初始值
                    } else {
                        this.spanArr.push(1); // 否则,依旧是一行
                        this.spanIndex = i;
                    }
                }
            }
        },
        // 合并列
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 0) {
                const _row = this.spanArr[rowIndex]; // 行数
                const _col = _row > 0 ? 1 : 0; // 列数
                return {
                    rowspan: _row,
                    colspan: _col
                };
            }
        },

最后,在created()方法中 或是你需要的方法中,调用getSpanArr()

created() {
    this.getSpanArr(this.nodesData); // nodesData是表格中的数据
},

最终效果