element-ui 表格數據根據某一列值相同進行行合並(包括序號列)並同列相同值進行合計


效果圖

需求后台返回jsonarr數組后,根據姓名值一直行進行合並,同時序號列合並,並計算當前人的各個項目耗時總和。

 

 

 實現思路:data中定義多個數組用於存放數據,包括

items: [],//序號,含冗余行
personWorkload: [],//個人合計
tableData: [],//table 數據顯示在最終頁面上數據
originalData: [],//table的備份數據 后台返回值直接賦值給備份數據
manageArr: [],//項目經理要合並的數組
managePos: 0,//項目經理要合並的數組的序號

 在獲取后台返回值方法中直接賦值給存放備份表格數據的數組,然后調用merage()方法進行每條數據過濾,然后把過濾組裝數據放入tabledata數組中,顯示在頁面上,重寫indexMethod方法進行序號自定義,返回項目經理耗時合計也在過濾每條數據時累計。

最終關鍵代碼

merage() {//每行數據過濾
//要合並的數組方法
this.tableData = this.originalData; //每次過濾之前都要把篩選之前的tableData重置
this.manageArr = [];
this.personWorkload=[];
this.items=[];
var cout = 1;//相同的序號
var perwl = 0;//個人合計
for (var i = 0; i < this.tableData.length; i++) {
//第一行必須存在
if (i === 0) {
this.manageArr.push(1);
this.managePos = 0;
this.items.push(1);
perwl = parseFloat(this.tableData[i].workLoad);

} else {
//判斷當前元素與上一個元素是否相同,managePos是manageArr內容的序號
if (this.tableData[i].perName === this.tableData[i - 1].perName) {
this.manageArr[this.managePos] += 1;
this.manageArr.push(0);
perwl += parseFloat(this.tableData[i].workLoad);
} else {
this.personWorkload.push(perwl);//當前值與上一個值不同,把上一個經理的累計耗時放入數組
perwl = parseFloat(this.tableData[i].workLoad);//累計值清0
cout++;//若不同則不需要合並行,cout+1。否則需要合並行,count不變
this.manageArr.push(1);
this.managePos = i;
}
this.items.push(cout);//不管需不需要合並都存放在原數組長度
}
if (i === this.tableData.length - 1) {
//如果是最后一行數據,需要特殊處理加入數組
this.personWorkload.push(perwl);
}
}
//關於每個人的合計耗時
// 1, 1, 2, 3, 4, 5, 5, 5, 5, 6, 6, 7, 8]----this.item中數據,含有冗余占位
//[26, 0, 1, 3.25, 32.625, 0, 12.5, 30.75---this.personWorkload數據,不含冗余,每個項目經理的合計值
//[26,26,0, 1, 3.25, 32.625,32.625,32.625,32.625, 0, 0, 12.5, 30.75] ---最終要行成的數據值
//填充冗余,若上層數組中序號相同,則合計數組中最后一個相同序號的數組賦值所有相同序號的值
//splice從指定位置插入數組 索引,刪除個數,插入值
for (var j = 0; j < this.items.length; j++) {
if (this.items[j] === this.items[j + 1]) {
this.personWorkload.splice(j + 1, 0, this.personWorkload[j]);
}
}


},
//自定義序號
indexMethod(index) {
//this.items [1, 1, 2, 2] 代表第1行,第2行,需要合並,第三行和第四行需要合並,
//indexMethod方法只循環合並后的次數,比如篩選后有6行,但是后台原始數據有10行,只循環6次,index表示合並前的索引值,
// 利用數組中自動補齊 合並行冗余數據根據索引值取值
//return 返回頁面中
//最后一列個人合計行,,在冗余數組中取數據
this.tableData[index].sumWorkload = this.personWorkload[index];

return this.items[index];//返回值序號
},
//合並行 原則上保存每個需要合並數據的首行,然后刪除其余行重復數據
arraySpanMethod({row, column, rowIndex, columnIndex}) {
//只有第1,2,7列進行合並
if (columnIndex === 0 || columnIndex === 1 || columnIndex === 6) {
//序號 姓名,投入總人天都需要根據項目經理合並
const _row_1 = this.manageArr[rowIndex];
const _col_1 = _row_1 > 0 ? 1 : 0; //如果被合並了_row=0則它這個列需要取消
return {
rowspan: _row_1,
colspan: _col_1
}
}
},

 

-----一個后台程序員的前端實現,如有更好實現方案,請交流,謝謝!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM