html部分
<el-table
:data="tableData"
:span-method="arraySpanMethod"
border
style="width: 100%">
<el-table-column
prop="id"
label="ID"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名">
</el-table-column>
<el-table-column
prop="amount1"
sortable
label="数值 1">
</el-table-column>
<el-table-column
prop="amount2"
sortable
label="数值 2">
</el-table-column>
<el-table-column
prop="amount3"
sortable
label="数值 3">
</el-table-column>
</el-table>
data数据
tableData: [{
id: '后勤部门',
name: '陈总',
amount1: '234',
amount2: '3.2',
amount3: 10
}, {
id: '后勤部门',
name: '陈总',
amount1: '165',
amount2: '4.43',
amount3: 12
}, {
id: '后勤部门',
name: '王小虎',
amount1: '324',
amount2: '1.9',
amount3: 9
}, {
id: '人力党务部',
name: '王小虎',
amount1: '621',
amount2: '2.2',
amount3: 17
}
, {
id: '人力党务部',
name: '老实说',
amount1: '539',
amount2: '4.1',
amount3: 15
}
, {
id: '人力党务部',
name: '老实说',
amount1: '539',
amount2: '4.1',
amount3: 15
}
, {
id: '人力党务部',
name: '老实说',
amount1: '539',
amount2: '4.1',
amount3: 15
}
, {
id: '人力党务部',
name: '王小虎',
amount1: '539',
amount2: '4.1',
amount3: 15
}
, {
id: '政企信息化',
name: '我来了',
amount1: '539',
amount2: '4.1',
amount3: 15
}
, {
id: '政企信息化',
name: '王小虎',
amount1: '539',
amount2: '4.1',
amount3: 15
}
],
spanArr:[]
一、合并单列的表格
将表格的span-method设置为'arraySpanMethod',getSpanArr可以放在获取表格数据后
// 表格合并处理
getSpanArr(){
// 当前遍历到第几行
let pos = 0
// 初始化spanArr,否则切换表格数据时,spanArr会累加
this.spanArr = []
for(let i = 0; i < this.tableData.length; i++){
if(i === 0){
this.spanArr.push(1)
pos = 0
}else{
if(this.tableData[i].id === this.tableData[i-1].id){
this.spanArr[pos] += 1
this.spanArr.push(0)
}else{
this.spanArr.push(1)
pos = i
}
}
}
}
// 合并表格列
arraySpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
let r = this.spanArr[rowIndex]
let c = this.spanArr[rowIndex] > 0 ? 1 : 0
return [r, c];
}
},
最终效果
二、合并多列的表格
合并第一列,第二列时
data定义
spanArr1:[],
spanArr2:[],
// 表格合并处理
getSpanArr(){
// 当前遍历到第几行
let pos1 = 0
let pos2 = 0
// 初始化spanArr,否则切换表格数据时,spanArr会累加
this.spanArr1 = []
this.spanArr2 = []
for(let i = 0; i < this.tableData.length; i++){
if(i === 0){
this.spanArr1.push(1)
this.spanArr2.push(1)
pos1 = 0
pos2 = 0
}else{
if(this.tableData[i].id === this.tableData[i-1].id){
this.spanArr1[pos1] += 1
this.spanArr1.push(0)
}else{
this.spanArr1.push(1)
pos1 = i
// 如果需要第二列与第一列保持同步,这三行不能注释
// this.spanArr2.push(1)
// pos2 = i
// continue
}
if(this.tableData[i].name === this.tableData[i-1].name){
this.spanArr2[pos2] += 1
this.spanArr2.push(0)
}else{
this.spanArr2.push(1)
pos2 = i
}
}
}
console.log(this.spanArr1);
},
// 合并表格列
arraySpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
let r = this.spanArr1[rowIndex]
let c = this.spanArr1[rowIndex] > 0 ? 1 : 0
return [r, c];
}
if (columnIndex === 1) {
let r = this.spanArr2[rowIndex]
let c = this.spanArr2[rowIndex] > 0 ? 1 : 0
return [r, c];
}
},
最终效果
注释掉上面三行的情况,第一列第二列单独合并
解开三行注释,第二列跟随第一列合并