<el-table v-loading="loading" :data="vetoList" border @selection-change="handleSelectionChange" :span-method="objectSpanMethod">
</el-table>
使用 :span-method="objectSpanMethod"
一、如果每一列依据的合并字段不同时
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 2) {
// 第三列依据khnr字段相同时合并
const currentId = row.khnr;
// 获取上一行相同列的id值
const preRow = this.vetoList[rowIndex - 1];
const preId = preRow ? preRow.khnr : null;
// 如果当前id值和上一行的id值相同,则将当前单元格隐藏
if (currentId === preId) {
return { rowspan: 0, colspan: 0 };
} else {
// 否则计算当前单元格应该跨越多少行
let rowspan = 1;
for (let i = rowIndex + 1; i < this.vetoList.length; i++) {
const nextRow = this.vetoList[i];
const nextId = nextRow.khnr;
if (nextId === currentId) {
rowspan++;
} else {
break;
}
}
return { rowspan, colspan: 1 };
}
}
if (columnIndex === 3) {
//第四列依据khxd字段相同时合并
const currentId = row.khxd;
// 获取上一行相同列的id值
const preRow = this.vetoList[rowIndex - 1];
const preId = preRow ? preRow.khxd : null;
// 如果当前id值和上一行的id值相同,则将当前单元格隐藏
if (currentId === preId) {
return { rowspan: 0, colspan: 0 };
} else {
// 否则计算当前单元格应该跨越多少行
let rowspan = 1;
for (let i = rowIndex + 1; i < this.vetoList.length; i++) {
const nextRow = this.vetoList[i];
const nextId = nextRow.khxd;
if (nextId === currentId) {
rowspan++;
} else {
break;
}
}
return { rowspan, colspan: 1 };
}
}
},
二、如果整体依据id值是否相同来合并时
this.postList = response.rows;
this.getSpanArr();
getSpanArr() {
this.spanArr = []
// 遍历数据
for (let i = 0; i < this.postList.length; i++) {
// 如果是第一个数据,就将列表spanArr添加一个1,表示暂时只有一个名字相同的、且将索引pos赋值为0
if (i === 0) {
this.spanArr.push(1);
this.pos = 0
} else {
// 判断当前元素与上一个元素是否相同
if (this.postList[i].id === this.postList[i - 1].id) {
// 如果相同就将索引为 pos 的值加一
this.spanArr[this.pos] += 1;
// 且将数组添加 0
this.spanArr.push(0);
} else {
// 如果元素不同了,就可以通过索引为 pos 的值知晓应该需要合并的行数
// 同时,我们再次添加一个值1,表示重新开始判断重复姓名的次数
this.spanArr.push(1);
// 同时 索引加一
this.pos = i;
}
}
}
console.log("索引数组:")
console.log(this.spanArr)
},
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
/* 此方法总共运行次数与有几列几行有关,如果有5列30行,那么都是从0开始作为第一行第一列,
(行,列):0,0 0,1 0,2 0,3 0,4 0,5 1,0...*/
// 0,1,5表示需要处理 第 1,2,5列的行进行合并处理
//需要合并的列
if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 8 || columnIndex === 9 || columnIndex === 10 || columnIndex === 11) {
/*
将需要合并的行数赋值给 _row,注意这里由上一个方法的输出可以知道,这里的值可以是 3或者0
当为 3 时,表示将当下的第 rowIndex+1 行与第 columnIndex+1 列所指向的单元格向下合并 _row 格
当为 0 时,表示将当下的第 rowIndex+1 行与第 columnIndex+1 列所指向的单元格隐藏
*/
const _row = this.spanArr[rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col
}
}
},