table根据字段合并单元格
全局 tableSpanUtils.ts
export const createObjectSpanMethod = (fields: string[], tableData: any) => {return ({ row, column, rowIndex, columnIndex }: any) => {const prop = column.propertyconst calculateRowspan = (field: any, rowIndex: any) => {let rowspan = 1for (let i = rowIndex + 1; i < tableData.length; i++) {if (tableData[i][field] === tableData[rowIndex][field]) {rowspan++} else {break}}return rowspan}const checkPreviousRow = (field: any, rowIndex: any) => {if (rowIndex > 0 && tableData[rowIndex][field] === tableData[rowIndex - 1][field]) {return true}return false}//序号单独处理if (prop === 'key') {const allFieldsMatch = fields.every((field) => checkPreviousRow(field, rowIndex))if (allFieldsMatch) {return { rowspan: 0, colspan: 0 }} else {const minRowspan = fields.reduce((min, field) => {const rowspan = calculateRowspan(field, rowIndex)return Math.min(min, rowspan)}, tableData.length - rowIndex)return { rowspan: minRowspan, colspan: 1 }}}if (fields.includes(prop)) {if (checkPreviousRow(prop, rowIndex)) {return { rowspan: 0, colspan: 0 }}return { rowspan: calculateRowspan(prop, rowIndex), colspan: 1 }}return { rowspan: 1, colspan: 1 }}
}
使用方法
// 引入 createObjectSpanMethod
import { createObjectSpanMethod } from '@/utils/tableSpanUtils'// 和 prop字短对应合并
const fields: string[] = ['merchant_name','card_status','type'
]
// html
<el-table :span-method="createObjectSpanMethod(fields, tableData)" class="defualtTable" :data="tableData"></el-table>