核心代码:
objectSpanMethod({
row, // 行
column, // 列
rowIndex, // 行索引
columnIndex, // 列索引
}) {
if (columnIndex === 0 || columnIndex === 1) {
// 获取当前单元格的值
const currentValue = row[column.property];
// 获取上一行相同列的值
const preRow = this.tableData[rowIndex - 1];
const preValue = preRow ? preRow[column.property] : null;
// 如果当前值和上一行的值相同,则将当前单元格隐藏
if (currentValue === preValue) {
return { rowspan: 0, colspan: 0 };
} else {
// 否则计算当前单元格应该跨越多少行
let rowspan = 1;
for (let i = rowIndex + 1; i < this.tableData.length; i++) {
const nextRow = this.tableData[i];
const nextValue = nextRow[column.property];
if (nextValue === currentValue) {
rowspan++;
} else {
break;
}
}
return { rowspan, colspan: 1 };
}
}
},
需要合并相同行的哪几列,就 if (columnIndex == x1 || columnIndex === x2 || .......),如代码中所示,为合并相同行中的前两列
整个方法的运行:
当表格需要进行合并时、整个渲染方式就发生了变化、之前可以看作以行为单位、一行一行渲染、而当你使用了 :span-method="objectSpanMethod"
变量后、渲染方式则改为一个单元格一个单元格渲染,即这个方法 objectSpanMethod
需要执行的次数是:列的个数 * 行数。
也就是说、它会按照这样的格式去调用方法:(行值,列结构值,行号,列号),具体例子为:
(row, column, 0, 0)、(row, column, 0, 1)、(row, column, 0, 2)、(row, column, 0, 3)、(row, column, 0, 4)
(row, column, 1, 0)、(row, column, 1, 1)、(row, column, 1, 2)、(row, column, 1, 3)、(row, column, 1, 4)