看效果
上重要代碼
<el-table :data="items" @row-click="rowclick" highlight-current-row :max-height="maxHeight" :header-cell-style="{'text-align':'center'}" show-summary :summary-method="getSummaries" >
show-summary是在表尾增加合計;
:summary-method="getSummaries"是自定義合計函數;
<el-table-column label="報表審核具體情況"> <template slot-scope="scope">{{ scope.row.fytjxxbqj.bbshjtqk }}</template> </el-table-column> <el-table-column label="駐粵人數" prop="zyrs"> <template slot-scope="scope">{{ scope.row.fytjxxbqj.zyrs }}</template> </el-table-column> <el-table-column label="駐湘人數" prop="zxrs"> <template slot-scope="scope">{{ scope.row.fytjxxbqj.zxrs }}</template> </el-table-column>
對於需要合計的列,需要加prop列屬性。由於我后端封裝的視圖層對象里面包含對象,所以前端顯示數據是這樣子的:{{ scope.row.fytjxxbqj.zyrs }},fytjxxbqj是后端的一個對象,但是列prop屬性只需要寫成對象里面的屬性(后面合計需要用到)
js的合計函數:
getSummaries(param) { const { columns, data } = param;//這里可以看出,自定義函數會傳入每一列,以及數據 const sums = []; columns.forEach((column, index) => {//遍歷每一列 if (index === 0) { sums[index] = "合計";//第一列顯示 合計 return; } if (index >= 12) {//這里是從索引12開始合計,前面的不合計 const values = data.map(item =>//遍歷每一行數據,得到相應列的所有數據形成一個新數組 Number(item.fytjxxbqj[column.property])//由於我后端封裝成對象,item.fytjxxbqj是獲得每一行數據fytjxxbqj對象,然后通過[column.property]列屬性獲得對象相應屬性的值,所以上面prop的值就設置成對象里面的屬性。如果不是對象的直接item[column.property]獲得相應的值,記得prop要設置 ); if (!values.every(value => isNaN(value))) {//這里是遍歷得到的每一列的值,然后進行計算 sums[index] = values.reduce((prev, curr) => { const value = Number(curr); if (!isNaN(value)) { return prev + curr; } else { return prev; } }, 0); sums[index] += " ";//可以在合計后的值后面加上相應的單位 } else { sums[index] = "";//如果列的值有一項不是數字,就顯示這個自定義內容 } } else { sums[index] = "";//索引12之前的列顯示這個自定義內容 } }); return sums;//最后返回合計行的數據 }
以上就是全部內容,記得需要合計的列加上prop屬性。