最近项目需要做一个统计账单的功能,将同一个月的账单明细进行合并,使用element-ui的table合并单元格功能,但需要自己实现合并的逻辑,代码贴在最后
<el-table :data="list" v-loading="loading" :span-method="objectSpanMethod" border >
<el-table-column label="账期" align="center" prop="billPeriod" />
<el-table-column label="应收明细" align="center" prop="feeItem" />
<el-table-column label="费用" align="center" prop="fee" />
<el-table-column label="应收合计" align="center" prop="totalFee" />
</el-table>
注意:这三个参数需要放到data外边,否则动态合并单元格会陷入死循环,objectSpanMethod这个方法内需要用到的输入参数都放到data外。
...
lastEndIndex: 0,
lastStartIndex: 0,
currentBillPeriodTotalFee: 0,
data() {
return {
}
}
...
//计算需要合并的行数
rowspan(startIndex) {
this.spanArr = [];
this.position = 0
let tableList = this.list;
let currentIndex = 1
this.currentBillPeriodTotalFee = 0
for(let index =0; index < tableList.length-1; index++) {
if (index >= startIndex) {
if (tableList[index + 1].billPeriod && tableList[index].billPeriod === tableList[index + 1].billPeriod) {//账期相同的进行合并
currentIndex = currentIndex + 1
if (this.currentBillPeriodTotalFee == 0) {
this.currentBillPeriodTotalFee = (tableList[index].fee*1) + (tableList[index + 1].fee*1)//计算’应收合计‘列的总金额
} else {
this.currentBillPeriodTotalFee = this.currentBillPeriodTotalFee + (tableList[index + 1].fee*1)
}
} else {
if (currentIndex > 1) {
this.lastStartIndex = startIndex
this.lastEndIndex = startIndex + currentIndex
} else {
this.currentBillPeriodTotalFee = (tableList[index].fee*1)
this.lastStartIndex = startIndex
this.lastEndIndex = startIndex
}
return currentIndex
}
}
}
if (currentIndex > 1) {
this.lastStartIndex = startIndex
this.lastEndIndex = startIndex + currentIndex
}
return currentIndex
},
//合并
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
let lastStartIndexTemp = this.lastStartIndex
let lastEndIndexTemp = this.lastEndIndex
if (columnIndex === 0 || columnIndex === 3) {//第一列和第四列需要合并
if (rowIndex > lastStartIndexTemp && rowIndex < lastEndIndexTemp) {
this.list[lastStartIndexTemp].totalFee = this.currentBillPeriodTotalFee.toFixed(2)
return {
rowspan: 0,
colspan: 0
};
} else {
let endIndexTemp = this.rowspan(rowIndex)
return {
rowspan: endIndexTemp,
colspan: 1
};
}
}
},