效果图
dom结构
<template>
<div>
<el-table
:data="tableData"
:span-method="summaryConf"
border
style="width: 100%; margin-top: 20px">
<el-table-column
prop="name"
label="名称"
width="180">
</el-table-column>
<el-table-column
prop="age"
label="年龄">
</el-table-column>
<el-table-column
prop="amount1"
label="数值 1(元)">
</el-table-column>
</el-table>
</div>
</template>
核心代码
<script>
import { mergeTableRow } from '@/utils/index'
export default {
components: {
},
props: {
},
data() {
return {
tableData: [
{
age: '111111',
name: '测试',
amount1: '1'
},
{
age: '2',
name: '测试',
amount1: '2'
},
{
age: '2',
name: '测试',
amount1: '3'
},
{
age: '4',
name: '测试',
amount1: '4'
},
{
age: '5',
name: '测试',
amount1: '5'
}
],
spanArr: [], // 合并表格
rowCols: ['name', 'age'], // 相同需要合并的字段
}
},
computed: {
},
created() {
this.getData()
},
mounted() {
},
watch: {
},
methods: {
getData() {
this.spanArr = mergeTableRow(
this.tableData,
this.rowCols
)
console.log(this.spanArr)
},
summaryConf({ row, column, rowIndex, columnIndex }) {
console.log(row, column, rowIndex, columnIndex, '111111111')
return this.objectSpanMethod({
row,
column,
rowIndex,
columnIndex
})
},
// 合并单元格
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
console.log(row, column, rowIndex, columnIndex, '222')
let index = this.rowCols.findIndex((v) => v === column.property)
if (index !== -1 && column.property === this.rowCols[index]) {
if (index === -1) {
index = 0
}
const _row = this.spanArr[index][rowIndex]
const _col = _row ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
}
}
}
</script>
合并方法–在utils文件下新建index方法
// table 表格合并 通用方法
// list table数据
// arr 需要合并的数据列的 prop 数组
const mergeTableRow = (list, arr) => {
let pos = 0
const len = []
const spanArr = []
arr.forEach((col, cIndex) => {
// 列 第几需要合并的个元素
const rows = []
list.forEach((row, rIndex) => {
// 多少行数据 最大可合并行数
if (!cIndex) {
len.push(1)
}
if (!rIndex) {
rows.push(1)
pos = rIndex
} else {
// 是否与上一行 元素值相同
if (list[rIndex][col] === list[rIndex - 1][col]) {
rows[pos] += 1
rows.push(0)
// 更新第一个元素相同值的个数
if (!cIndex) {
len[rIndex] = rows[pos]
}
// 超出最大个数 重新赋值
if (rows[pos] > len[rIndex]) {
rows[pos] -= 1
pos = rIndex
rows[pos] += 1
}
} else {
rows.push(1)
pos = rIndex
}
}
})
spanArr.push(rows)
})
return spanArr
}
export { mergeTableRow }