elementui官网的表格单元格合并方法是针对静态数据的,判断是写死的。
rowspan是合并的行数:为1表示不变;为0表示去除该单元格,后面的单元格会向上往这格填; colspan同理
而实际情况表格数据往往是动态的。
现如下图,需要将表格前四列的相同数据项合并。
直接上代码:
<el-table :data="budgetList" border :span-method="objectSpanMethod" highlight-current-row height="100%">
<el-table-column prop="accName" label="会计科目"></el-table-column>
<el-table-column prop="unemploy" label="失业保险"></el-table-column>
<el-table-column prop="employ" label="就业专项"></el-table-column>
<el-table-column prop="deptOrgName" label="科室"></el-table-column>
<el-table-column prop="projectName" label="项目"></el-table-column>
<el-table-column prop="budgetaryAmount" label="金额"></el-table-column>
<el-table-column prop="moneySource" label="资金渠道" :formatter="columnFormat"></el-table-column>
</el-table>
data() {
return {
budgetList: [],//表格
spanArr: [],//二维数组,用于存放单元格合并规则
position: 0,//用于存储相同项的开始index
}
}
methods: {
//表格
budgetListinit() {
let para = {};
this.$http({
method: "post",
url: "...",
data: para
})
.then(res => {
this.budgetList = res.data || [];
this.rowspan(0,'accName');
this.rowspan(1,'unemploy');
this.rowspan(2,'employ');
this.rowspan(3,'deptOrgName');
})
.catch(err => {});
},
rowspan(idx, prop) {
this.spanArr[idx] = [];
this.position = 0;
this.budgetList.forEach((item,index) => {
if( index === 0){
this.spanArr[idx].push(1);
this.position = 0;
}else{
if(this.budgetList[index][prop] === this.budgetList[index-1][prop] ){
this.spanArr[idx][this.position] += 1;//有相同项
this.spanArr[idx].push(0); // 名称相同后往数组里面加一项0
}else{
this.spanArr[idx].push(1);//同列的前后两行单元格不相同
this.position = index;
}
}
})
},
//表格单元格合并
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
for(let i = 0; i<4; i++) {
if(columnIndex === i){
const _row = this.spanArr[i][rowIndex];
const _col = _row>0 ? 1 : 0;
// console.log('第'+rowIndex+'行','第'+i+'列','rowspan:'+_row,'colspan:'+_col)
return {
rowspan: _row,
colspan: _col
}
}
}
},
}