element-ui官网提供了表格行合并的方法,但是官方demo过于简单用取余的方法将行两两合并 ,实际开发中需求显然复杂的多,今天我就行记录一下我在开发中从获取动态数据后,对数据进行处理,并进行啊行合并的方法:
https://element.eleme.cn/#/zh-CN/component/table 先看懂官方的案例再自行上手 案例比较简单不多解释了
从后台获取的数据
[{"orgId":59,"activityId":3,"name":"a","num":1,"orgName":"逐日信息科技"},
{"orgId":59,"activityId":3,"name":"b","num":2,"orgName":"逐日信息科技"},
{"orgId":59,"activityId":3,"name":"c","num":13,"orgName":"逐日信息科技"},
{"orgId":59,"activityId":3,"name":"d","num":12,"orgName":"逐日信息科技"},
{"orgId":66,"activityId":3,"name":"e","num":11,"orgName":"逐日信息科技1"},
{"orgId":66,"activityId":3,"name":"f","num":11,"orgName":"逐日信息科技1"}]
需要的展示效果 (需要将orgId相同数据的orgName合并展示 )
html表格代码很简单
先附上处理后的数据 多了一个rowspan属性以标记合并行的位置信息
[{"orgId":59,"activityId":3,"name":"a","num":1,"orgName":"逐日信息科技","rowspan":4},
{"orgId":59,"activityId":3,"name":"b","num":2,"orgName":"逐日信息科技","rowspan":0},
{"orgId":59,"activityId":3,"name":"c","num":13,"orgName":"逐日信息科技","rowspan":0},
{"orgId":59,"activityId":3,"name":"d","num":12,"orgName":"逐日信息科技","rowspan":0},
{"orgId":66,"activityId":3,"name":"e","num":11,"orgName":"逐日信息科技1","rowspan":2},
{"orgId":66,"activityId":3,"name":"f","num":11,"orgName":"逐日信息科技1","rowspan":0}]
从后台获取并处理数据的方法 以及合并展示的方法
//获取并处理数据
handleParticipator() {
list({}).then((res) => {//发送http请求
this.participatorList = res.rows;
//处理数据
for (let i = this.participatorList.length - 1; i > 0; i--) {
//从后向前遍历
if (!this.participatorList[i].rowspan) {
//设置初始值(可理解为:每个数据项必定占一行)
this.participatorList[i].rowspan = 1;
}
if (
this.participatorList[i].orgId == this.participatorList[i - 1].orgId
) {
//当前公司名与前一个数据的公司相同时 设置rowspan(前数据一项与下一行的相同时 合并一行)
this.participatorList[i - 1].rowspan =
this.participatorList[i].rowspan + 1;
this.participatorList[i].rowspan = 1;
}
}
});
},
//合并展示
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
if (row.rowspan != 1) {
return {
rowspan: row.rowspan,
colspan: 1,
};
} else {
return {
rowspan: 0,
colspan: 0,
};
}
}
},