<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 {
initArr: [],
rowCount: 0,
tableData: [
{
id: '12987122',
name: '王小虎',
amount1: '234',
amount2: '3.2',
amount3: 10,
},
{
id: '12987122',
name: '王小虎',
amount1: '222',
amount2: '3.6',
amount3: 14,
},
{
id: '12987122',
name: '王小虎',
amount1: '6565',
amount2: '312',
amount3: 989,
},
{
id: '12987123',
name: '王小虎',
amount1: '165',
amount2: '4.43',
amount3: 12,
},
{
id: '12987123',
name: '王小虎',
amount1: '1321',
amount2: '413',
amount3: 132,
},
{
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,
},
],
}
},
created() {
this.init()
},
methods: {
init() {
this.initArr = []
this.rowCount = 0
for (let i = 0; i < this.tableData.length; i++) {
// 如果当 i == 0 说明数据是第一行, 需要重新赋值
if (i == 0) {
//说明这一行数据被显示出来
this.initArr.push(1)
//重置当前的计数器
this.rowCount = 0
}
// 说明不是从第一行开始遍历的
else {
// 判断当前的指定数据是否和之前的指定数据值相同
if (this.tableData[i].id == this.tableData[i - 1].id) {
// 如果相同就需要将 this.initArr 的数据自加
this.initArr[this.rowCount] += 1
// 同时需要将 this.initArr push一个0 表示下一行不用显示
this.initArr.push(0)
}
// 说明 当前的数据和上一行的指定数据不同
else {
// 说明当前一行的数据需要显示
this.initArr.push(1)
// 重新给计数器赋值
this.rowCount = i
}
}
}
},
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
// 用于给第一列的table判断是否合并
if (columnIndex === 0) {
// this.initArr[rowIndex] 取出当前存放行的合并状态
const row = this.initArr[rowIndex]
// 判断当前的 列是否需要显示
const col = row > 0 ? 1 : 0
return {
rowspan: row,
colspan: col,
}
}
},
},
}
</script>