合并主要靠span-method属性直接上代码,这里以vue3为例,vue2类似:
<template>
<div>
<!-- table列表 -->
<el-table :data="tableList" :span-method="arraySpanMethod">
<el-table-column v-for="item in dataColumn" :key="item.key" :prop="item.key" :label="item.label"> </el-table-column>
</el-table>
</div>
</template>
<script setup>
let tableList = [
{
id: '1298712211',
name: '小张',
amount1: '234',
amount2: '3.2',
amount3: 10,
},
{
id: '12987122',
name: '小王',
amount1: '234',
amount2: '3.2',
amount3: 9,
},
{
id: '12987123',
name: '小吴',
amount1: '234',
amount2: '4.43',
amount3: 12,
},
{
id: '12987124',
name: '小明',
amount1: '324',
amount2: '1.9',
amount3: 9,
},
{
id: '12987125',
name: '小黑',
amount1: '324',
amount2: '2.2',
amount3: 17,
},
{
id: '12987126',
name: '小白',
amount1: '539',
amount2: '4.1',
amount3: 15,
},
{
id: '12987127',
name: '小小',
amount1: '511139',
amount2: '41.1',
amount3: 15,
},
{
id: '129871217',
name: '小赵',
amount1: '511139',
amount2: '41.1',
amount3: 15,
},
{
id: '129817127',
name: '小李',
amount1: '511139',
amount2: '41.1',
amount3: 15,
},
]
const dataColumn = ref([
{
key: 'name',
label: '名字'
},
{
key: 'amount1',
label: '列一'
},
{
key: 'amount2',
label: '列二'
},
{
key: 'amount3',
label: '列三'
},
])
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
let spanArr = getSpanArr(tableList, column.property);
const _row = spanArr[rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col,
};
}
const getSpanArr = (data, spanKey) => {
let spanArr = [];
let pos = "";
for (let i = 0; i < data.length; i++) {
if (i === 0) {
spanArr.push(1);
pos = 0;
} else {
// 判断当前元素与上一个元素是否相同
if (data[i][spanKey] === data[i - 1][spanKey]) {
spanArr[pos] += 1;
spanArr.push(0);
} else {
spanArr.push(1);
pos = i;
}
}
}
return spanArr;
}
</script>
<style lang="scss" scoped>
:deep(.el-table__cell) {
border: 1px solid #ebeef5;
}
</style>
效果如下: