首先来看下官网上如何写的
<template>
<div>
<el-table
:data="tableData"
:span-method="objectSpanMethod"
border
style="width: 100%; margin-top: 20px">
<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>
</div>
</template>
<script>
export default {
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
}]
};
},
methods: {
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
if (rowIndex % 2 === 0) {
return {
rowspan: 2,
colspan: 1
};
} else {
return {
rowspan: 0,
colspan: 0
};
}
}
}
}
};
</script>
显然这种固定写法并不能满足我们日常开发中的需求
再请求到后台数据之后如果数据不是按你想合并字段排序的话,这时候需要多做一步排序,把需要合并的那个字段分组显示,这里就不过多赘述了(这个分组一般后台都能做)。
接下来就讲一下如何操作
首先再data里定义两个变量
data () {
return {
merge: [], // 存放需要合并的行
subscript: '' // 需要合并行下标
}
},
之后再调用接口获取到数据之后运行获取merge和subscript的方法
getMergeSubSceipt (data) {
if (data) {
for (var i = 0; i < data.length; i++) {
if (i === 0) {
this.merge.push(1)
this.subscript = 0
} else {
// 判断当前元素与上一个元素是否相同
// 根据相同id进行合并,根据需要可进行修改
if (data[i].team === data[i - 1].team) {
this.merge[this.subscript] += 1
this.merge.push(0)
} else {
this.merge.push(1)
this.subscript = i
}
}
}
}
},
到这就已经把数据处理完了接下来就是处理el-table的合并方法文章来源:https://uudwc.com/A/Y6gZx
<el-table :data="memberList" :span-method="objectSpanMethod">
</el-table>
objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
const _row = this.merge[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
}
文章来源地址https://uudwc.com/A/Y6gZx