代碼:
<el-table :data="listArr" border style="width: 99%" id="mainFrame" :span-method="objectSpanMethod" show-summary :summary-method="getSummaries"> <el-table-column prop="userName" label="姓名" align="center"></el-table-column> <el-table-column prop="logMonth" label="日期" align="center"> <template slot-scope="scope"> <span>{{scope.row.logMonth | logMonth}}</span> </template> </el-table-column> ...... </el-table>
methods: { objectSpanMethod({ row, column, rowIndex, columnIndex }){ let that = this that.spanArr = [] // 頁面展示的數據,不一定是全部的數據,所以每次都清空之前存儲的 保證遍歷的數據是最新的數據。以免造成數據渲染混亂 that.pos = 0 let data = this.listArr
//遍歷數據 data.forEach((item, index) => { if (index === 0) { //判斷是否是第一項(取決於你准備合並表格第幾項) this.spanArr.push(1) this.pos = 0 } else {//不是第一項時,就根據標識去存儲 if (data[index].userId === data[index - 1].userId) {// 查找到符合條件的數據時每次要把之前存儲的數據+1 this.spanArr[this.pos] += 1 this.spanArr.push(0) } else {// 沒有符合的數據時,要記住當前的index this.spanArr.push(1) this.pos = index } } }) if (columnIndex === 0) {
// 頁面列表上 表格合並行 -> 第幾列(從0開始)
// 需要合並多個單元格時 依次增加判斷條件即可
// 數組存儲的數據 取出
const _row = this.spanArr[rowIndex] const _col = _row > 0 ? 1 : 0 return { rowspan: _row, colspan: _col } } else {//不可以return {rowspan:0, colspan: 0} 會造成數據不渲染, 也可以不寫else,eslint過不了的話就返回false return false } }, }