element合并单元格
声明一个数组变量plantMergeArr 用来装数据(只合并单个单元格)
setMergeArr (data) {
this.mergeSpanArrIndex = 0
this.plantMergeArr = []
for (var i = 0; i < data.length; i++) {
if (i === 0) {
this.plantMergeArr.push(1)
this.mergeSpanArrIndex = 0
} else {
// 判断当前元素与上一个元素是否相同 plantId是要合并的那一列的字段名
if (data[i].plantId === data[i - 1].plantId) {
this.plantMergeArr[this.mergeSpanArrIndex] += 1
this.plantMergeArr.push(0)
} else {
this.plantMergeArr.push(1)
this.mergeSpanArrIndex = i
}
}
}
},
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) { // 合并第一列所有数据相同行
const _row = this.plantMergeArr[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
},
在获取到table数据之后讲数据传到setMergeArr(tableData)中
多个单元格的时候可以声明两个变量
// 合并单元格
setMergeArr (data) {
this.mergeSpanArrIndex1 = 0
this.mergeSpanArr1 = []
this.mergeSpanArrIndex2 = 0
this.mergeSpanArr2 = []
for (var i = 0; i < data.length; i++) {
if (i === 0) {
this.mergeSpanArr1.push(1);
this.mergeSpanArrIndex1 = 0
this.mergeSpanArr2.push(1);
this.mergeSpanArrIndex2 = 0
} else {
// 判断当前元素与上一个元素是否相同
if (data[i].costType === data[i - 1].costType) {
this.mergeSpanArr1[this.mergeSpanArrIndex1] += 1;
this.mergeSpanArr1.push(0);
} else {
this.mergeSpanArr1.push(1);
this.mergeSpanArrIndex1= i;
}
if (data[i].top === data[i - 1].top) {
this.mergeSpanArr2[this.mergeSpanArrIndex2] += 1;
this.mergeSpanArr2.push(0);
} else {
this.mergeSpanArr2.push(1);
this.mergeSpanArrIndex2 = i;
}
}
}
},
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) { // 合并第一列所有数据相同行
const _row = this.mergeSpanArr1[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
if (columnIndex === 1) { // 合并第一列所有数据相同行
const _row = this.mergeSpanArr2[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
},```
在data中声明两组变量
mergeSpanArr1: [], // 空数组,记录每一行的合并数
mergeSpanArrIndex1: 0, // mergeSpanArr的索引
mergeSpanArr2: [], // 空数组,记录每一行的合并数
mergeSpanArrIndex2: 0 // mergeSpanArr的索引
tabledata拿到数据的时候赋值给`this.setMergeArr(this.letfTableData)`
在el-table上设置属性 :span-method=“objectSpanMethod”
就完成了