最近使用element ui做的一個表格,現在又加了一個新需求,就是要求可以合併單元格.
從後臺拿到的數據格式如下:
data= [
{
"number": 4,
"dataTypeName": "食品生產",
"dataType": "1",
"details": [
{
"wscCou": 3,
"cou": 3,
"scCou": 0,
"abbreviation": "華涇"
},
{
"wscCou": 1,
"cou": 1,
"scCou": 0,
"abbreviation": "漕河涇"
}
]
},
{
"number": 130,
"dataTypeName": "藥品零售",
"dataType": "2",
"details": [
{
"wscCou": 24,
"cou": 24,
"scCou": 0,
"abbreviation": "楓林"
},
{
"wscCou": 9,
"cou": 9,
"scCou": 0,
"abbreviation": "斜土"
},
{
"wscCou": 8,
"cou": 8,
"scCou": 0,
"abbreviation": "康健"
},
{
"wscCou": 8,
"cou": 8,
"scCou": 0,
"abbreviation": "天平"
}
]
}
]
element ui table有合併單元格的功能,但是由於後臺返回我的數據和文檔不一致,所以我這要手動更改一下數據格式.
下面是我遍歷修改數據格式的方法.
data.forEach((item,index)=>{
if(item.details && item.details.length > 0){
item.details.forEach(itemDetail=>{
let obj = Object.assign({},itemDetail,{
dataType : item.dataType,
dataTypeName : item.dataTypeName,
number : item.number,
})
this.tableData.push(obj);
})
}
})
console.log(this.tableData);
接着按照文檔上面使用***span-method***進行合併
<el-table :data="tableData" border empty-text="暫無數據" :span-method="mergeTable">
<el-table-column prop="dataTypeName" label="類型名稱"></el-table-column>
<el-table-column prop="number" label="證件總數量"></el-table-column>
<el-table-column prop="abbreviation" label="所"></el-table-column>
<el-table-column prop="wscCou" label="圖片未上傳數"></el-table-column>
<el-table-column prop="scCou" label="圖片上傳數"></el-table-column>
<el-table-column prop="cou" label="彙總數"></el-table-column>
</el-table>
mergeTable({ row, column, rowIndex, columnIndex }){
let arr = [];
let pos = 0;
for(let i = 0;i<this.tableData.length;i++){
if(i === 0 ){
arr.push(1);
pos = 0
}else{
if(this.tableData[i].dataType === this.tableData[i-1].dataType){
arr[pos] +=1;
arr.push(0);
}else{
arr.push(1);
pos = i;
}
}
}
//此處arr拿到的是相對應的行合併數,打印出來是[2,0,4,0,0,0],
//比如第一元素爲2,表示第一行應該向下合併2行(即第一行的rowspan爲2),
//第二個元素的rowspan爲0,就讓它“消失”。
//接下來按照要求,我們,我們只合並第一列和第二列
if (columnIndex === 0 || columnIndex ===, 1) {
const _row = arr[rowIndex];
const _col = _row > 0 ? 1 : 0;
return { // [0,0] 表示這一行不顯示, [2,1]表示行的合併數
rowspan: _row,
colspan: _col
}
}
}