实际效果图如下
下面是表格的具体内容
<template>
<el-table
:data="tableData"
:span-method="objectSpanMethod"
border
height="700px"
style="width: 100%;height:50vh; margin-top: 20px">
<el-table-column type="index"></el-table-column>
<el-table-column
prop="id"
label="ID"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
height='200'>
<template v-slot="{row}">
<span class="accent_color">{{row.name}}</span>
</template>
</el-table-column>
<el-table-column
prop="amount1"
label="数值 1(元)" height='200'>
</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-column
width="100px"
prop="sss"
label="操作">
<template v-slot="{row}"><el-button icon="el-icon-delete"></el-button></template>
</el-table-column>
</el-table>
</template>
下面是表格的具体数据
data(){
return{
tableData: [
{
id: '129871222222',
name: 'Tom2',
amount1: '234',
amount2: '3.2',
amount3: 10,
sss: 1,
},
{
id: '129871222',
name: 'Tom',
amount1: '234',
amount2: '3.2',
amount3: 10,
sss: 1,
},
{
id: '129871222',
name: 'Tom2',
amount1: '234',
amount2: '3.2',
amount3: 10,
sss: 1,
},
{
id: '12987122',
name: 'Tom',
amount1: '234',
amount2: '3.2',
amount3: 10,
sss: 1,
},
{
id: '12987122',
name: 'Tom',
amount1: '234',
amount2: '3.2',
amount3: 10,
sss: 1,
},
{
id: '12987122',
name: 'Tom',
amount1: '234',
amount2: '3.2',
amount3: 10,
sss: 1,
},
{
id: '129871222',
name: 'Tom',
amount1: '234',
amount2: '3.2',
amount3: 10,
sss: 1,
},
],
}
},
关键的代码是处理数据,通过for循环遍历处理,对需要合并的列的值进行比较,达到合并效果,最后必须将值进行倒序处理否则无效 this.tableData.reverse()
mounted() {
//由于没有调接口,测试数据处理在mounted()钩子里
this.tableData.reverse()//倒序处理数据,此处可以不写
//增加属性
this.tableData.map(item => {
item.rowspan = 1
})
//遍历数组,并比较id进行合并
for (let i = 0; i < this.tableData.length; i++) {
if (i + 1 < this.tableData.length && this.tableData[i].id === this.tableData[i + 1].id) {
this.tableData[i + 1].rowspan = this.tableData[i].rowspan + 1
this.tableData[i].rowspan = 0
}
}
console.log(this.tableData)
this.tableData.reverse()//必须加倒序否则合并表格无效
},
最后是 合并表格的主要方法是 :span-method="objectSpanMethod",写在methods方法里面
methods:{
objectSpanMethod({row, column, rowIndex, columnIndex}) {
//columnIndex 默认是从0开始,由于加了序号那列,'id'那列的columnIndex 就是1
if (columnIndex === 1) {
return {
rowspan: row.rowspan,
colspan: 1
}
}
//此处合并的是'name'那列
if (columnIndex === 2) {
return {
rowspan: row.rowspan,
colspan: 1
}
}
//此处合并的是操作那栏 'sss'
if (columnIndex === 6) {
return {
rowspan: row.rowspan,
colspan: 1
}
}
},
}
最后说明一下,方法是我的一个朋友刘总(小刘)帮助下,进一步修改完成的。希望对大家有帮助。