效果如下
直接上代码
template
<el-table v-loading="listLoading" align="center" border :data="tableList" :span-method="objectSpanMethod">
<el-table-column v-for="(item, index) in tableCom" :key="index" align="center" :label="item.label" :min-width="100" :prop="item.prop">
<template slot-scope="scope">
<div v-if="index === 2" class="inlinListMain">
<div v-for="item2 in scope.row.dataInfo" :key="item2.activityType" class="inlinList">{{ item2.activityTypeName }}</div>
</div>
<div v-if="index === 3" class="inlinListMain">
<div v-for="(item2, index2) in scope.row.dataInfo" :key="index2" class="inlinList">{{ item2.count }}</div>
</div>
<span v-else>{{ scope.row[item.prop] }}</span>
</template>
</el-table-column>
</el-table>
data
data(){
return{
tableList: [],//表格数据,数据为接口获取
tableCom: [
{ label: '工程名称', prop: 'projectName' },
{ label: '标段', prop: 'segmentName' },
{ label: '人员类别', prop: 'activityTypeName' },
{ label: '人员数量', prop: 'count' },
{ label: '合计', prop: 'total' },
],//表格标题
mergeObj: {},//合并列需要的存储对象
mergeArr: ['projectName'],//需要合并的对象(tableList里的某个属性)
sameObjIndex: 0,//合并统计
sameObj: {},
}
}
methods
// 处理表格数据(合并行)
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
// 判断列的属性
if (this.mergeArr.indexOf(column.property) !== -1) {
// 判断其值是不是为0
if (this.mergeObj[column.property][rowIndex]) {
return [this.mergeObj[column.property][rowIndex], 1]
} else {
// 如果为0则为需要合并的行
return [0, 0]
}
}
},
// getSpanArr方法
getSpanArr(data) {
this.mergeArr.forEach((key, index1) => {
let count = 0 // 用来记录需要合并行的起始位置
this.mergeObj[key] = [] // 记录每一列的合并信息
data.forEach((item, index) => {
// index == 0表示数据为第一行,直接 push 一个 1
if (index === 0) {
this.mergeObj[key].push(1)
this.sameObj[this.sameObjIndex] = item.count
} else {
// 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
if (item[key] === data[index - 1][key]) {
this.mergeObj[key][count] += 1
this.mergeObj[key].push(0)
this.sameObj[this.sameObjIndex] += item.count
} else {
// 如果当前行和上一行其值不相等
count = index // 记录当前位置
this.mergeObj[key].push(1) // 重新push 一个 1
this.sameObjIndex++
this.sameObj[this.sameObjIndex] = 0
// this.sameObj[this.sameObjIndex] = item.count
}
}
})
})
},
在初始化完成tableList表格数据后,调用this.getSpanArr(this.tableList)即可
需要注意的是,因为数据结构的不同,在合并的时候需要区分具体的某些字段
css
.el-table .cell {
padding-left: 0 !important;
padding-right: 0 !important;
}
.el-table--small .el-table__cell {
padding: 0 !important;
}
.el-table__header-wrapper .el-table__cell {
padding: 8px !important;
}
.inlinList {
padding: 10px 0;
border-bottom: 1px solid #e7e5e5;
}
.inlinListMain .inlinList:last-child {
border-bottom: none;
}
因为element ui自带的样式限制,在更改样式的时候,最好在前面加一个类,用style lang=“scss”