<template>
<div>
<el-table :data="tableData" border style="width: 60%" :span-method="objectSpanMethod">
<el-table-column prop="name" label="姓名" />
<el-table-column prop="amount1" label="数值1" />
<el-table-column prop="amount2" label="数值2" />
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: "Tom", amount1: 10, amount2: 15 },
{ name: "Tom", amount1: 11, amount2: 16 },
{ name: "Jack", amount1: 12, amount2: 17 },
{ name: "Andy", amount1: 13, amount2: 18 },
{ name: "Andy", amount1: 14, amount2: 19 },
],
};
},
mounted() {
console.log("结果:", this.getSpanNumber(this.tableData, "name"));
},
methods: {
//合并方法
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex == 0) {
//合并相同的名字
let nameSpan = this.getSpanNumber(this.tableData, "name");
return {
rowspan: nameSpan[rowIndex],
colspan: 1,
};
}
},
//获取要合并的行数
getSpanNumber(data, prop) {
//data要处理的数组,prop要合并的属性,比如name
//数组的长度,有时候后台可能返回个null而不是[]
let length = Array.isArray(data) ? data.length : 0;
if (length > 0) {
//用于标识位置
let position = 0;
//用于对比的数据
let temp = data[0][prop];
//要返回的结果
let result = [1];
//假设数据是AABCC,我们的目标就是返回20120
for (let i = 1; i < length; i++) {
if (data[i][prop] == temp) {
//标识位置的数据加一
result[position] += 1;
//当前位置添0
result[i] = 0;
} else {
//不相同时,修改标识位置,该位置设为1,修改对比值
position = i;
result[i] = 1;
temp = data[i][prop];
}
}
//返回结果
return result;
} else {
return [0];
}
},
},
};
</script>
结果: