ElementUI Table组件使用 span-method 合并相同单元格

时间:2025-04-08 08:10:23

相关背景 

Element-UI 官网的 span-method 属性案例演示中没有给出局部相同数据的合并使用场景

使用属性

Table Attributes
参数 说明 类型
span-method 合并行或列的计算方法 Function({row, column,rowIndex,columnIndex})

span-method: 方法的参数是一个对象,包含row 行、 column 列、rowIndex 当前行、columnIndex 当前列号;该函数返回值可以说一个包含两个元素的数组(第一个元素代表 rowspan,第二个元素代表 colspan),也可以是一个键名为 rowspan 和 colspan 的对象。

使用细节

1. 后台返回的表格数据格式如下:

data() {
    return {
        tableData: [
            {id: '001',name: '李白'}, 
            {id: '001',name: '李白'}, 
            {id: '777',name: '杜甫'}, 
            {id: '777',name: '杜甫'},
            {id: '777',name: '杜甫'}
        ]
    }
}

2. 计算属性中将表格数据按将要合并的字段进行分类(例如: id)

computed: {
	tableDataColumn() {
      const dataObject = {}
      ((item, index) => {
        const id = 
        if (dataObject[id]) {
          dataObject[id].push(index)
        } else {
          dataObject[id] = []
          dataObject[id].push(index)
        }
      })
      return dataObject
    }
}

3. methods中操作:

arraySpanMethod({ row, column, rowIndex, columnIndex }) {
    if (columnIndex === 0) { // 第一列相同数据合并
        if (rowIndex > 0 &&  === [rowIndex - 1].id) {
          return {
            rowspan: 0,
            colspan: 0
          }
        } else {
          const id = 
          const rows = [id]
          const length = 
          return {
            rowspan: length,
            colspan: 1
        }
      }
   }
}