vue - element UI table合并行合并列
Max.Bai
2019-12
先看下效果:
0. 基本思路
合并行:如果上一行和这一行值一样,开始计算span,不一样就返回合并span
合并列:如果上一列和这一列值一样,开始计算span,不一样就返回合并span
1. table设置
<el-table
:data="dataSource"
:border="true"
:header-cell-style="{ 'font-weight': 'normal', 'text-align': 'center' }"
:cell-style="{ 'text-align': 'center' }"
size="mini"
style="width: 100%"
:span-method="arraySpanMethod"
>
<el-table-column type="index" width="40"></el-table-column>
<el-table-column prop="product_name" label="产品名称" width="180"></el-table-column>
<el-table-column prop="cap_name" label="能力名称" width="180"></el-table-column>
<el-table-column prop="2019-12" label="2019-12" width="80"></el-table-column>
<el-table-column prop="2020-01" label="2020-01" width="80"></el-table-column>
<el-table-column prop="2020-02" label="2020-02" width="80"></el-table-column>
</el-table>
2. 数据格式
dataSource: [
{
product_name: "aaaa",
cap_name: "na1",
"2019-12": 1,
"2020-01": 1,
"2020-02": 0
},
{
product_name: "aaaa",
cap_name: "na2",
"2019-12": 0,
"2020-01": 1,
"2020-02": 1
},
{
product_name: "bbbb",
cap_name: "nb1",
"2019-12": 1,
"2020-01": 1,
"2020-02": 0
},
{
product_name: "bbbb",
cap_name: "nb2",
"2019-12": 0,
"2020-01": 1,
"2020-02": 1
},
{
product_name: "bbbb",
cap_name: "nb3",
"2019-12": 0,
"2020-01": 1,
"2020-02": 1
},
],
3. 关键代码合并js
arraySpanMethod({ row, column, rowIndex, columnIndex }) {
// 合并行 产品名字相同合并
if (columnIndex === 1) {
if(rowIndex ===0 || row.product_name != this.dataSource[rowIndex-1].product_name){
let rowspan = 0;
this.dataSource.forEach(element => {
if(element.product_name === row.product_name){
rowspan ++;
}
});
return [rowspan, 1];
}else {
return [0, 0];
}
}
//合并列 月份值都为1 的合并
if (columnIndex > 2) {
let colspan = 0;
let colkeys = Object.keys(row);
let currentindex = columnIndex-1;
if (row[colkeys[currentindex]] === 1) {
if(row[colkeys[currentindex-1]] != row[colkeys[currentindex]]){
for(let i = currentindex;i<colkeys.length;i++) {
if (row[colkeys[i]]===1)
{
colspan ++;
} else {
break;
}
}
return [1, colspan];
} else {
return [0, 0];
}
}
}
}