效果
后端动态传回要渲染的表头和表信息,通过动态计算的方式自动合并列,效果图如下
实现方法
- 后端请求接口获取表头和数据信息
// 获取指标列表
getDataTypeList() {
const form = { subjectId: this.tableId }
subjecttemplate.list(form)
.then(result => {
if (result.code === '200') {
//我这里是动态获取最大目录级别,自动拼接的,可以完全由后端返回
for(var i = 1;i<= result.data.maxLevel;i++){
this.tableColumns.push({
label: '级别'+i,
prop: 'chapterLevel'+i
})
}
this.tableColumns = this.tableColumns.concat(this.defaultColumns)
//获取表数据
this.billList = result.data.dataMapList
this.checkValue()
} else {
this.$message.error(result.msg)
}
})
},
2.渲染表头和表数据
//把tableColumns和billList传入,自动渲染
<div style="width: 100%;background-color: rgba(242, 242, 242, 1);height: 100%;overflow: auto;overflow-x: hidden">
<ics-table
:data="billList" border style="width: 99%;padding-top: 10px;padding-left: 20px;overflow: auto" :span-method="objectSpanMethod">
<ics-table-column v-for="column in tableColumns" :key="column.prop" align="center" :label="column.label" :prop="column.prop" />
</ics-table>
</div>
3.通过计算实现列合并
计算方法
checkValue(){
let packNoDot = 0;
//遍历所有的表头信息
this.tableColumns.forEach((column, num) => {
this.packNoList = []
packNoDot = 0
this.billList.forEach((item, index) => {
//对于不想列合并的列进行排除
if(column.prop !== 'name') {
if (index === 0) {
this.packNoList.push(1);
} else {
if (item[column.prop] === this.billList[index - 1][column.prop]) {
//计算当前列值和前一列是否相同,相同则+1
this.packNoList[packNoDot] += 1;
this.packNoList.push(0);
} else {
packNoDot = index;
this.packNoList.push(1);
}
}
}else {
//不就行列合并的就直接数组全是1
this.packNoList.push(1);
}
});
this.all[num] = this.packNoList;
});
},
计算完成后会获得一个列合并数组,例如[2,0,3,0,0],就代表这一列第一行和第二行合并,第三行到第五行合并。
最后还有一个方法:
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
const _row = this.all[columnIndex][rowIndex];
const _col = _row > 0 ? 1 : 0;
//该形式为行合并
return {
rowspan: _row,
colspan: _col,
};
},
用于在步骤二中表头那里使用