废话不多说,看代码
代码中出现的未知变量
- this.mergeFiles : 数组类型. 包含需要合并的字段名
- mergeFiles: 需要合并的字段, 默认空字符串不合并
- mergeKey : 需要合并字段的辅助判断字段, 非必选, 当传入mergeKey的时候,无论上下行数据mergeFiles是否一致,只按照传入的字段进行比较合并, 与mergeFiles 共同作用, 注意: 当使用mergeKey的时候,不判断空值. 即空值也能合并
props: {
// 当前table绑定 modalForm 下的字段, 如: modalForm.childList 的 childList . 默认为childList
modalKey: { type: String, default: () => 'childList' },
// 父级表单
modalForm: {
type: Object,
default: () => {},
},
// 需要合并的字段
mergeFiles: {
type: Array,
default: () => [],
},
// 需要合并字段的辅助判断字段, 非必选, 与mergeFiles 共同作用, 注意: 当使用mergeKey的时候,不判断空值. 即空值也能合并
mergeKey: { type: String, default: () => '' },
},
// 非空判断
isNotEmpty(value) {
return value !== undefined && value !== null && value !== '';
},
// 合并单元格
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
// 获取需要合并的列的字段集合
const fields = this.mergeFiles;
// 当前单元格的数据
const cellValue = row[column.property];
// 1.判断当前列是否 是父组件传来的需要合并的列/ 并且当前值不为空 或者是需要强制合并的列
if (
fields.includes(column.property) &&
(this.isNotEmpty(cellValue) || this.mergeKey)
) {
// 上一行数据
const preRow = this.modalForm[this.modalKey][rowIndex - 1];
// 下一行数据
let nextRow = this.modalForm[this.modalKey][rowIndex + 1];
// 2. 如果上一行的数据与当前行的数据相同,返回 rowspan: 0, colspan: 0,表示合并(隐藏当前单元格)
// 如果有辅助判断字段,则必须相同才能合并
if (this.mergeKey) {
if (preRow && preRow[this.mergeKey] === row[this.mergeKey]) {
return { rowspan: 0, colspan: 0 };
} else {
// 反之, 若上一行数据与当前行数据不一样,那么循环判断,下一行数据若是与当前数据相同,那么合并当前单元格
let countRowsapn = 1; // 用于合并计数单元格
while (
this.mergeKey &&
nextRow &&
nextRow[this.mergeKey] === row[this.mergeKey]
) {
nextRow =
this.modalForm[this.modalKey][++countRowsapn + rowIndex];
}
if (countRowsapn > 1) {
return {
rowspan: countRowsapn,
colspan: 1,
};
}
return { rowspan: 1, colspan: 1 };
}
} else {
if (preRow && preRow[column.property] === cellValue) {
return { rowspan: 0, colspan: 0 };
} else {
// 反之, 若上一行数据与当前行数据不一样,那么循环判断,下一行数据若是与当前数据相同,那么合并当前单元格
let countRowsapn = 1; // 用于合并计数单元格
while (nextRow && nextRow[column.property] === cellValue) {
nextRow =
this.modalForm[this.modalKey][++countRowsapn + rowIndex];
}
if (countRowsapn > 1) {
return {
rowspan: countRowsapn,
colspan: 1,
};
}
return { rowspan: 1, colspan: 1 };
}
}
}
},