需求: 将某一列值相同且相连的行合并
1, 模板:
<el-table :data="tableData" :span-method="objectSpanMethod">
<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" label="数值 1(元)"> </el-table-column>
<el-table-column prop="amount2" label="数值 2(元)"> </el-table-column>
<el-table-column prop="amount3" label="数值 3(元)"> </el-table-column>
</el-table>
2, 数据
{
data() {
return {
tableData: [{
id: '12987122',
name: '王小虎',
amount1: '234',
amount2: '3.2',
amount3: 10
}, {
id: '12987123',
name: '王小虎',
amount1: '165',
amount2: '4.43',
amount3: 12
}, {
id: '12987124',
name: '王小虎',
amount1: '324',
amount2: '1.9',
amount3: 9
}, {
id: '12987125',
name: '张三',
amount1: '621',
amount2: '2.2',
amount3: 17
}, {
id: '12987126',
name: '张三',
amount1: '539',
amount2: '4.1',
amount3: 15
}]
}
}
}
3, 处理方法
{
methods: {
objectSpanMethod({ rowIndex, columnIndex }) {
if (columnIndex === 1) {
// 'name' 需要合并的键值
const nameSpan = this.getSpanNumber(this.tableData, 'name')
return {
rowspan: nameSpan[rowIndex],
colspan: 1
}
}
},
//获取要合并的行数
getSpanNumber(tableData, prop) {
const arrNumber = tableData.reduce(
(prev, next) => {
if (prev.currIndex > 0) {
if (prev.name === next[prop]) {
prev.number[prev.nameIndex] += 1
prev.number[prev.currIndex] = 0
} else {
prev.name = next[prop]
prev.nameIndex = prev.currIndex
prev.number[prev.currIndex] = 1
}
}
prev.currIndex += 1
return prev
},
{
currIndex: 0,
number: [1],
nameIndex: 0,
name: tableData[0] && tableData[0][prop]
}
)
return arrNumber.number
}
}
}
4, 效果