一、合并效果
二全部代码
<template>
<div class="table-wrap">
<el-table
:data="tableData"
:span-method="handleSpanMethod"
:cell-style="{ background: '#FFFFFF' }"
border
>
<el-table-column prop="id" label="id" align="center" />
<el-table-column prop="name" label="名称" align="center" />
<el-table-column prop="amount1" label="身高" align="center" />
<el-table-column prop="amount2" label="体脂" align="center" />
<el-table-column prop="amount3" label="年龄" align="center" />
</el-table>
</div>
</template>
<script>
export default {
name: 'CellMerge',
data() {
return {
tableData: [{
id: '1',
name: '王小虎',
amount1: '165',
amount2: '3.2',
amount3: 10
}, {
id: '1',
name: '王小虎',
amount1: '162',
amount2: '4.43',
amount3: 12
}, {
id: '1',
name: '王we虎',
amount1: '621',
amount2: '1.9',
amount3: 9
}, {
id: '2',
name: '王we虎',
amount1: '621',
amount2: '2.2',
amount3: 17
}, {
id: '3',
name: '王小虎',
amount1: '621',
amount2: '4.1',
amount3: 15
}],
// 合并单元格
column1Arr: [], // column1
column1Index: 0, // column1索引
column2Arr: [], // column2
column2Index: 0, // column2索引
column3Arr: [], // column3
column3Index: 0, // column3索引
}
},
mounted(){
this.mergeTable(this.tableData)
},
methods: {
// 合并表格
mergeTable(data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
if (i === 0) {
// 第一行必须存在,以第一行为基准
this.column1Arr.push(1) // column1
this.column1Index = 0
this.column2Arr.push(1) // column2
this.column2Index = 0
this.column3Arr.push(1) // column3
this.column3Index = 0
} else {
// 判断当前元素与上一元素是否相同
// column1
if (
data[i].id === data[i - 1].id
) {
this.column1Arr[this.column1Index] += 1
this.column1Arr.push(0)
} else {
this.column1Arr.push(1)
this.column1Index = i
}
// column2
if (
data[i].name === data[i - 1].name && data[i].id === data[i - 1].id
) {
this.column2Arr[this.column2Index] += 1
this.column2Arr.push(0)
} else {
this.column2Arr.push(1)
this.column2Index = i
}
// column3
if (
data[i].amount1 === data[i - 1].amount1 && data[i].name === data[i - 1].name&& data[i].id === data[i - 1].id
) {
this.column3Arr[this.column3Index] += 1
this.column3Arr.push(0)
} else {
this.column3Arr.push(1)
this.column3Index = i
}
}
}
}
},
handleSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
// 第一列 column1
const _row_1 = this.column1Arr[rowIndex]
const _col_1 = _row_1 > 0 ? 1 : 0
return {
rowspan: _row_1,
colspan: _col_1
}
} else if (columnIndex === 1) {
// 第二列 column2
const _row_2 = this.column2Arr[rowIndex]
const _col_2 = _row_2 > 0 ? 1 : 0
return {
rowspan: _row_2,
colspan: _col_2
}
} else if (columnIndex === 2) {
// 第二列 column2
const _row_3 = this.column3Arr[rowIndex]
const _col_3 = _row_3 > 0 ? 1 : 0
return {
rowspan: _row_3,
colspan: _col_3
}
}
}
}
}
</script>
<style>
</style>