废话不多说,直接上代码,里面有详细注释!
<template>
<div>
<el-table
border
:span-method="spanMethod"
:data="tableList"
>
<el-table-column label="省" align="center" width="200">
<template slot-scope="{row}">
<div>{{ row.province }}</div>
</template>
</el-table-column>
<el-table-column label="名字" align="center" width="250">
<template slot-scope="{row}">
<p>{{ row.name }}</p>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: 'HomePage',
data() {
return {
tableList: [
{ province: '广东省', name: '张三' },
{ province: '广东省', name: '张三' },
{ province: '广东省', name: '张三' },
{ province: '广西省', name: '张三' },
{ province: '湖南省', name: '张三' },
{ province: '湖南省', name: '张三' },
{ province: '湖南省', name: '张三' },
{ province: '湖南省', name: '张三' }
],
indexArray: []
}
},
mounted() {
this.getIndexArray('province')
},
methods: {
getIndexArray(e) {
const indexObject = {}
this.tableList.forEach((item, index) => {
if (indexObject[item[e]]) {
indexObject[item[e]].push(index)
} else {
indexObject[item[e]] = []
indexObject[item[e]].push(index)
}
})
console.log(indexObject, 'indexObjectindexObjectindexObject')
for (const k in indexObject) {
if (indexObject[k].length > 1) {
this.indexArray.push(indexObject[k])
}
}
console.log(this.indexArray, ' this.indexArray')
},
spanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
for (let i = 0; i < this.indexArray.length; i++) {
const element = this.indexArray[i]
for (let j = 0; j < element.length; j++) {
const item = element[j]
if (rowIndex === item) {
if (j === 0) {
return {
rowspan: element.length,
colspan: 1
}
} else if (j !== 0) {
return {
rowspan: 0,
colspan: 0
}
}
}
}
}
}
}
}
}
</script>
最后实现的效果
