最近做的项目涉及到很多单元格合并问题,element-ui组件对于单元格合并的处理虽然很灵活,但是需要事先计算好每个单元格合并的rowspan和colspan,直接在span-method属性中计算实现起来有点困难,所以我拿到列表后先把每条数据的需要合并的rowspan计算出来然后直接在span-method属性中返回即可。上代码:
export const merge = function( colArr, list ) { var allProps = []; colArr.forEach((props, index) => { allProps.push(...props); list = getLevel(props, allProps, list); }); return list; }; //组装层 function getLevel(props, allProps, list) { var rowKey = {}; for (var item of list) { let propInfo = getPropStr(allProps, item); if (rowKey[propInfo.key]) { rowKey[propInfo.key].children.push(item); } else { let obj = propInfo; obj.children = [item]; rowKey[propInfo.key] = obj; } } let info = []; for (var key in rowKey) { rowKey[key].children.forEach((item, index) => { if (index == 0) { item = Object.assign( item, getMergeInfo(props, rowKey[key].children.length) ); } else { item = Object.assign(item, getMergeInfo(props, 0)); } info.push(item); }); } return info; } //获取合并信息 function getMergeInfo(props, num) { let obj = {}; props.forEach(item => { obj[item + "_merge"] = { rowspan: num, colspan: 1 }; }); return obj; } // 把属性的值拼接在一起,并和属性的值一起返回。 function getPropStr(props, info) { let obj = {}; let propStr = props.map(item => { obj[item] = info[item]; return info[item]; }); obj.key = propStr.toString(); return obj; }
span-method合并函数:
objectSpanMethod({ row, column, rowIndex, columnIndex }) { if (row[column.property + "_merge"]) { return row[column.property + "_merge"]; } else { return { rowspan: 1, colspan: 1 }; } },
导进去直接调用:
var colArr = [["id", "grade"], ["class"]]; var list = [ { id: 1, grade: 1, class: 1, name: "张三" }, { id: 1, grade: 1, class: 1, name: "李四" }, { id: 1, grade: 1, class: 2, name: "王五" }, { id: 1, grade: 1, class: 2, name: "找六" }, { id: 2, grade: 2, class: 7, name: "张三_1" }, { id: 2, grade: 2, class: 7, name: "李四_1" }, { id: 2, grade: 2, class: 3, name: "王五_1" }, { id: 2, grade: 2, class: 3, name: "找六_1" } ]; this.tableDate = merge(colArr, list);
备注:colArr是要合并的层级。示例中id和grade是第一次,class是第二层。
list是数据列表。