注:以下代码仅支持向下合并单元格,不支水平合并单元格。
<el-table :data="list" :span-method="cellRowSpanConfig" border> <el-table-column label="序号" type="index" align="center" fixed> <template slot-scope="scope"> <span>{{ (pager.page - 1) * pager.size + scope.$index + 1 }}</span> </template> </el-table-column> <el-table-column label="name" prop="name"></el-table-column> <el-table-column label="age" prop="age"></el-table-column> <el-table-column label="address" prop="address"></el-table-column> </el-table>
export default { data() { return { list: [ { name: '张三', age: 18, address: '中/国/北/京' }, { name: '张三', age: 19, address: '中/国/新/疆' }, { name: '李四', age: 19, address: '中/国/西/藏' }, { name: '王五', age: 19, address: '中/国/青/海' }, { name: '王五', age: 18, address: '中/国/北/京' }, { name: '王五', age: 18, address: '中/国/北/京' }, ], mergeableFields: ['age', 'name'], // 需要合并的列 pager: { page: 1, size: 30, total: 6, }, }; }, methods: { cellRowSpanConfig({ row, column, rowIndex, columnIndex }, elTableDataKey = "list") { let self = this; let field = column.property; let config = { rowspan: 1, // >0:向下合并的单元格个数(==1时自己与自己合并即不与其它单元格合并),==0:当前单元格被合并了 colspan: 1, }; if (self.mergeableFields && Array.isArray(self.mergeableFields) && self.mergeableFields.length && self.mergeableFields.includes(field)) { let value = row[field]; if (rowIndex == 0 || (rowIndex > 0 && value !== self[elTableDataKey][rowIndex - 1][field])) { let span = 0; // 在「el-table :data="list"」中的当前行向下找,看有几行需要合并 topLevel: for (let i = rowIndex; i < self[elTableDataKey].length; i++) { const v = self[elTableDataKey][i][field]; // 恒等的原因: ''==0 is true if (v === value) { span++; } else { break topLevel; } } config.rowspan = span; } // 与上一行的值相同时表示当前行被合并了 else if (rowIndex > 0 && value === self[elTableDataKey][rowIndex - 1][field]) { config.rowspan = 0; } } return config; }, }, }