前言

el-table作为前端开发中最常用的数据表格组件,行合并需求在实际项目中频繁出现,但官方文档介绍较为简略。本文结合开发中的实际需求,提供了一种简单、易用的el-table实现行合并的参考方案。

数据格式及实现效果图参考

1.实现效果图

image.png

2.数据格式

image.png

产品名称、sku编码、sku数量的数据来自数组orderProductVOS

具体实现

1.扁平化数组生成新的表格数据

   flattenData(data) {
      const result = []
      data.forEach((order, index) => {
        const rowIndexObj = { rowIndex: index + 1 }  //记录索引值防止合并行后序号不连续
        order.orderProductVOS.forEach(product => {
          result.push({
            ...order,
            ...rowIndexObj,
            productName: product.productName,
            skuCode: product.productSkuCode,
            quantity: product.productQuantity
          })
        })
      })
      this.flattenedData = result
    }

2.合并行的计算方法

objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 定义不需要合并的列(通过列名识别)
      const notMergeColumns = ['产品名称', 'sku编码', 'sku数量']

      // 判断当前列是否是不需要合并的列
      const isNotMergeColumn = notMergeColumns.includes(column.label)

      if (isNotMergeColumn) {
        // 不需要合并的列,保持原样
        return { rowspan: 1, colspan: 1 }
      } else {
        // 需要合并的列
        // 找到当前订单号(该表格的订单号是唯一的,可以根据情况取一个唯一的值)
        const currentOrderNumber = row.orderNumber

        // 计算当前订单在表格中的起始行索引
        let startRowIndex = rowIndex
        while (startRowIndex > 0 && this.flattenedData[startRowIndex - 1].orderNumber === currentOrderNumber) {
          startRowIndex--
        }

        // 如果当前行是订单的第一行,则合并整个订单的行数
        if (rowIndex === startRowIndex) {
          // 计算当前订单的总行数
          let rowCount = 0
          while (startRowIndex + rowCount < this.flattenedData.length &&
            this.flattenedData[startRowIndex + rowCount].orderNumber === currentOrderNumber) {
            rowCount++
          }

          return { rowspan: rowCount, colspan: 1 }
        } else {
          // 非第一行,不显示
          return { rowspan: 0, colspan: 0 }
        }
      }
    },

3.表格组件的模板代码

      <el-table 
      :data="flattenedData" 
      border 
      style="width: 100%" 
      :header-cell-style="{height:'45px',color:'#303133'}"
      header-align="left" 
      :max-height="tableHeight" 
      v-loading="loadingTable" 
      @selection-change="handleSelectionChange" 
      :span-method="objectSpanMethod"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column label="序号" prop="rowIndex" width="50" align="center" fixed="left">
        </el-table-column>
        ...
      </el-table>

结语

按照上述方法即可实现表格的行合并效果。需要注意的是,如果在列属性中使用 type="index" 自动生成序号,行合并后可能会导致序号显示不连续。为解决这一问题,可以在外层循环中手动维护一个索引变量,通过该变量动态生成连续的序号,从而确保序号的连贯性。

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]