需求:
任意列顯示后臺傳過來的總計數。
最后結果:
這里需要補充的是:我這里的合計數是從后臺計算好傳過來的,而不是前端計算的,所以這里不涉及table合計的方法,如需要,elementUI 的 table 中就有,可以參考那里。
我這里實現的主要是如何進行任意列的顯示。
element UI 的table 中有顯示合計的方法:
所以,如果要最后一行顯示合計,直接在table設置上show-summary即可。
但是這往往無法滿足我們的需求,就比如我這里需要顯示的是后臺傳過來的數值,而且是任意我想要顯示的列。所以我就要去自定義它的合計方法。
let getSum = function(param) {
const {
columns,
data
} = param;
const sums = [];
columns.forEach((column, index) => {
if(index === 0) {
sums[index] = '合計';
return;
}
switch(column.property) {
case "money":
sums[index] = (this.footer.moneySum / 100).toFixed(2) + '元’; //值取自后臺
break;
case "profit":
sums[index] = this.footer.profitSum / 100 + '元’; //值取自后臺
break;
default:
break;
}
});
return sums;
}
使用column.property去匹配他的每一列的命名,然后賦值。
最后別忘了將該方法在 methods 中注冊:
另外如何從后臺取值也在這里記錄一下:
后臺傳過來的值是一個數組形式:
[{profitSum: 2, companyId: "094aea82-8c1e-44ec-994e-a950c7515bda", moneySum: 1000}]
而其實前臺我就只需要數組的第一個object中的兩個參數的值,所以需要在前臺轉化一下,將其轉化為object形式。
那么首先就要在date中去注冊一下:
let data = () => {
return {
rows: [],
page: 1,
sort: '',
order: '',
filters: filters,
listLoading: false,
total: 20,
formVisible: false,
gridData: [],
filtersDialog: filtersDialog,
footer: { //{}形式
moneySum: 0,
profitSum: 0
},
}
}
然后在接收的時候去轉化一下:
loadPage(para).catch(e => this.listLoading = false).then(res => {
this.gridData = res.data.rows;
this.listLoading = false;
if(res.data.footer && res.data.footer.length > 0) {
this.footer.moneySum = res.data.footer[0].moneySum
this.footer.profitSum = res.data.footer[0].profitSum
} else {
this.footer.moneySum = 0
this.footer.profitSum = 0
}
});
判斷了一下是否為空,然后做轉化。