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];
}
}
}
}