在项目中遇到需要合并表格相同列,开始采用的方式为
// data中的配置
// 需要合并的行配置
mergeMap: {
0: { span: 1 },
1: { parent: true, span: 2 }, // 槽车外输
3: { parent: true, span: 3 }, // 返装船
6: { parent: true, span: 3 } // 卸船
},
// js方法
objectSpanMethod({ column, rowIndex, columnIndex }) {
// 处理项目列的合并
if (columnIndex === 1) {
if (this.mergeMap[rowIndex]) {
return { rowspan: this.mergeMap[rowIndex].span, colspan: 1 };
}
return { rowspan: 0, colspan: 0 };
}
},
后面不满足多列合并的需求及代码的健壮性,将代码进行优化,可以进行特定列表格合并及全局代码合并
dataMethod(data, isH = []) {
const newArray = [...data];
newArray.forEach((i, index) => {
const dataI = newArray[index];
Object.keys(dataI).forEach((j) => {
if (index === 0) {
this.spanObj[j] = [1];
this.pos[j] = 0;
} else {
const [e, k] = [dataI, data[index - 1]];
if (k && e[j] === k[j] && (!isH?.length || isH.includes(j))) {
this.spanObj[j][this.pos[j]] += 1;
this.spanObj[j].push(0);
} else {
this.spanObj[j].push(1);
this.pos[j] = index;
}
}
});
});
return this.spanObj;
}
// 在span-method中使用
objectSpanMethod({ column, rowIndex, columnIndex }) {
if (columnIndex === 1 || columnIndex === 2) {
const _row = this.spanObj[column.property][rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col
};
}