合并场景:如果id一样,则主表列合并,子表列不做合并,可实现单行、多行合并,亲测!!!
展示效果如图示:
组件代码:
// table组件 :span-method="objectSpanMethod" 一定要有这个方法,合并逻辑都在这个里面<el-table:data="dataList":span-method="objectSpanMethod"border><el-table-column prop="className" label="班级" /><el-table-column prop="name" label="姓名" /><el-table-column prop="sex" label="性别" /><el-table-column prop="dataType" label="科目" /><el-table-column prop="score" label="分数" /></el-table>
js代码:
//数据格式
dataList: [{id:"1",className:"3-1",name:"张三",sex:"男",dataType:"数学",score:"81"},{id:"1",className:"3-1",name:"张三",sex:"男",dataType:"英语",score:"33"},{id:"1",className:"3-1",name:"张三",sex:"男",dataType:"历史",score:"66"},{id:"2",className:"3-2",name:"李四",sex:"女",dataType:"科学",score:"13"},{id:"2",className:"3-2",name:"李四",sex:"女",dataType:"英语",score:"90"},],//合并的js逻辑 需要合并多少列就写几列
objectSpanMethod({row, column, rowIndex, columnIndex}) {const _row = this.flitterData(this.dataList).one[rowIndex];const _col = _row > 0 ? 1 : 0;//合并第一列if (columnIndex === 0) {return {rowspan: _row,colspan: _col,};}//合并第二列if (columnIndex === 1) {return {rowspan: _row,colspan: _col,};}//合并第三列if (columnIndex === 2) {return {rowspan: _row,colspan: _col,};}},flitterData(arr) {let spanOneArr = [];let concatOne = 0;arr.forEach((item, index) => {if (index === 0) {spanOneArr.push(1);} else {// 如果id一样,就合并,根据自己的需求来改,id换为要比较的列名if (item.id == arr[index - 1].id) {spanOneArr[concatOne] += 1;spanOneArr.push(0);} else {spanOneArr.push(1);concatOne = index;}}});return {one: spanOneArr,};},