dat为表格数据,aa为表头数据
initTable(data, aa) {
let mergeRow = [] //行的合并值
let mergeCol = [] // 列的合并值
// 合并的是行,向下合并
aa.forEach((column, colIndex) => {
let currentCellValue = null
let rowspan = 1
for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
const cellValue = data[rowIndex][column.dataIndex]
if (rowIndex === 0) {
currentCellValue = cellValue
} else if (cellValue === currentCellValue) {
rowspan++
} else {
if (rowspan > 1) {
mergeRow.push({
row: rowIndex - rowspan,
col: colIndex,
rowspan,
colspan: 1,
})
}
currentCellValue = cellValue
rowspan = 1
}
if (rowIndex === data.length - 1 && rowspan > 1) {
mergeRow.push({
row: rowIndex - rowspan + 1,
col: colIndex,
rowspan,
colspan: 1,
})
}
}
})
// 合并的是列,向右合并
data.forEach((row, rowIndex) => {
const cellValues = {} // 用于存储每列的值
aa.forEach((column, colIndex) => {
const cellValue = row[column.dataIndex]
if (!cellValues[cellValue]) {
cellValues[cellValue] = {
startCol: colIndex,
colspan: 1,
}
} else {
cellValues[cellValue].colspan++
}
})
// 合并单元格
for (const value in cellValues) {
const { startCol, colspan } = cellValues[value]
if (colspan > 1) {
mergeCol.push({
row: rowIndex,
col: startCol,
rowspan: 1,
colspan: colspan,
})
}
}
})
//有些重复的单元格,要进行格子更改,不管是先合并列还是先合并行,可以根据需求更改次合并的格子
mergeRow.map((i) => {
mergeCol.map((k) => {
if (i.row === k.row && i.col === k.col) {
k.col++, k.colspan--
}
})
})
this.mergeCells = []
this.mergeCells = this.mergeCells.concat(mergeRow, mergeCol) //将数据赋值给合并的组件
},
实现表格动态根据后端数据进行行和列的合并
效果图