展示
代码
<el-table :data="tableData" border style="width: 100%" :span-method="objectSpanMethod"><el-table-column prop="date" label="Date" width="180" align="center" /><el-table-column prop="name1" label="Name1" width="180" align="center" /><el-table-column prop="name2" label="Name2" width="180" align="center" /><el-table-column prop="class" label="class" width="180" align="center" /><el-table-column prop="address" label="Address" />
</el-table>
const tableData = ref([{date: '2016-05-04',name1: 'Tom',name2: 'Tom',class: '三年级一班',address: 'No. 189, Grove St, Los Angeles'},{date: '2016-05-03',name1: 'Tom',name2: 'Tom',class: '三年级一班',address: 'No. 189, Grove St, Los Angeles'},{date: '2016-05-02',name1: 'Tom',name2: 'Tom',class: '三年级一班',address: 'No. 189, Grove St, Los Angeles'},{date: '2016-05-02',name1: 'Tom',name2: 'Tom',class: '三年级一班',address: 'No. 189, Grove St, Los Angeles'},{date: '2016-05-01',name1: 'Tom',name2: 'Tom',class: '三年级一班',address: 'No. 189, Grove St, Los Angeles'}
])const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {let rowspan = 1,colspan = 1// 合并列// 自行判断哪两个字段需要合并,相同值即代表要合并// 并且需要自行判断当前合并字段所在的列下标,如示例中的name1的列下标为1,name2的列下标为2// 则把name1的列下标的colspan设为2(即占两个单元格),那么name2的列下标的colspan则必须为0,表示不占单元格if (row.name1 == row.name2) {if (columnIndex == 1) {colspan = 2rowspan = 1} else if (columnIndex == 2) {colspan = 0rowspan = 0}}// 合并行// 定义需要合并的列字段,有哪些列需要合并,就自定义添加字段即可const fields = ['date']// 当前单元格的数据const cellValue = row[column.property]// 判断只合并定义字段的列数据if (cellValue && fields.includes(column.property)) {const prevRow = tableData.value[rowIndex - 1] //上一行数据let nextRow = tableData.value[rowIndex + 1] //下一行数据// 当上一行的单元格数据等于当前行数据时,当前行单元格隐藏if (prevRow && prevRow[column.property] === cellValue) {colspan = 0rowspan = 0} else {// 反之,则循环判断若下一行数据等于当前行数据,则当前行开始进行合并单元格let countRowspan = 1 // 用于合并计数多少单元格while (nextRow && nextRow[column.property] === cellValue) {nextRow = tableData.value[++countRowspan + rowIndex]}if (countRowspan > 1) {rowspan = countRowspan}}}return {rowspan,colspan}
}
完结。