element-UI表格table实现表格行的动态合并

1,820 阅读2分钟

本文主要举个项目中真实实例,方便各位跟我一样在实际项目开发中碰到的需求功能的开发。(可直接拿来使用的)

饿了么table组件官方实例:element-cn.eleme.io/#/zh-CN/com…

在实际开发过程中,官方实例根本无法满足需求,实际需求一般都是动态的合并而不是固定怎么合并的,所以这时就需要我们对其进行处理。

大致思路就是:先将查询出的列表数据分出哪几列哪几行需要进行合并并且合并多少行或多少列,这些数据记录放进一个空数组中,合并的时候再根据这个数组进行相应的合并。

.Vue 文件

<div style="padding-top: 20px">
  <el-table
    ref="table" row-key="id"
    :data="statisticsData"
    style="width: 100%;min-width:600px;"
    :span-method="objectSpanMethod"
  >
    <el-table-column label="发票类型" >
      <template slot-scope="{ row }"> {{row.type == '51' ? '电子发票' : '纸质发票'}}</template>
    </el-table-column>
    <el-table-column prop="minInvoiceNum" label="最小号码"></el-table-column>
    <el-table-column prop="maxInvoiceNum" label="最大号码" ></el-table-column>
    <el-table-column label="发票号码段" >
      <template slot-scope="{ row }">
          <div v-for="(item,index) in row.inovoiceNumRanges" :key="index">{{item.invoiceNumBegin}} - {{item.invoiceNumEnd}}</div>
      </template>
    </el-table-column>
  </el-table>
</div>

vue.js(script)文件:

export default {
  data () {
    return {
      statisticsData: [],
      spanArr: [], // 遍历数据时,根据相同的标识去存储记录
      pos: 0 // 二维数组的索引
    }
  },
  methods: {
    getNumStatistics () {
      this.$api({
        url: 'getinvoiceNumStatistics',
        data: {
          ...this.searchForm
        }
      }).then(res => {
        if (res && res.data) {
          this.statisticsData = res.data
          let data = res.data
          this.getSpanArr(data)
        }
      })
    },
    getSpanArr (data) {
      let that = this
      // 页面展示的数据,不一定是全部的数据,所以每次都清空之前存储的 保证遍历的数据是最新的数据。以免造成数据渲染混乱
      that.spanArr = []
      that.pos = 0
      // 遍历数据
      data.forEach((item, index) => {
        // 判断是否是第一项
        if (index === 0) {
          this.spanArr.push(1)
          this.pos = 0
        } else {
          // 不是第一项时,就根据标识去存储
          if (data[index].inovoiceNumRanges === data[index - 1].inovoiceNumRanges) {
            // 查找到符合条件的数据时每次要把之前存储的数据+1
            this.spanArr[this.pos] += 1
            this.spanArr.push(0)
          } else {
            // 没有符合的数据时,要记住当前的index
            this.spanArr.push(1)
            this.pos = index
          }
        }
      })
      console.log(this.spanArr, this.pos)
    },
    // 列表方法
    objectSpanMethod ({ rowIndex, columnIndex }) {
      // 页面列表上 表格合并行 -> 第几列(从0开始)
      // 需要合并多个单元格时 依次增加判断条件即可
      if (columnIndex === 3) {
        // 二维数组存储的数据 取出
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
        // 不可以return {rowspan:0, colspan: 0} 会造成数据不渲染, 也可以不写else,eslint过不了的话就返回false
      } else {
        return false
      }
    }
  }
}

最终效果: