el-table合并单元格

原效果:
在这里插入图片描述

这样看起来就很难受,用户体验极其不好,所以,我们把相同的单元格进行合并。

直接上代码

<el-table v-loading="loading" :data="AstationFxList"
                  :stripe="true"
                  :span-method="objectSpanMethod" //加入这个方法
</el-table>

在你查询出来所有数据的方法中

getList() {
      this.loading = true;
      listAstationFx(this.queryParams).then(response => {
        this.AstationFxList = response.rows;
        this.getSpanArr(this.AstationFxList); //把数据添加到这个方法中
        this.total = response.total;
        this.loading = false;
      });
    },

编写此 getSpanArr()方法

//获取合并配置明细
    getSpanArr(data) {
      // data就是我们从后台拿到的数据
      this.spanArr = [];
      this.pos = 0;
      
      this.spanArrdfytsl = [];//合并电费用途统计数量
      this.posdfytsl = 0;//合并电费用途统计数量索引
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          //设置table表格行号、设置合并参数,以便相同参数合并
          this.spanArr.push(1);
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].city === data[i - 1].city) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          }else{
            this.spanArr.push(1);
            this.pos = i;
          }
			if (data[i].name=== data[i - 1].name) {
	            this.spanArr[this.pos] += 1;
	            this.spanArr.push(0);
          	}else{
	            this.spanArr.push(1);
	            this.pos = i;
          }
          //如果我们合并的是多列,那么就继续if()else,但是要将数据添加的数组要重新声明。
          if (data[i].sumdfyfv === data[i - 1].sumdfyfv) {
            this.spanArrdfytsl[this.posdfytsl] += 1;
            this.spanArrdfytsl.push(0);
          }else{
            this.spanArrdfytsl.push(1);
            this.posdfytsl = i;
          }
        }
      }
    },

最后合并

//合并单元格
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if(columnIndex ===0 ){
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {rowspan: _row,colspan: _col}
      }
      if(columnIndex === 1){
        const _row = this.spanArrdfytsl[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {rowspan: _row,colspan: _col}
      }
    },

最后效果图
在这里插入图片描述

此文章是为了记录遇到的问题,方便以后的查看。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐