v-12 ElementUI 合并单元格

2019-06-05  本文已影响0人  陌上桑_浅

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

// template
<template>
  <div>
    <el-table
      :data="data"
      :span-method="objectSpanMethod"
      border
      style="width: 100%; margin-top: 20px">
      <el-table-column
        prop="id"
        label="ID"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名">
      </el-table-column>
      <el-table-column
        prop="amount1"
        label="数值 1(元)">
      </el-table-column>
      <el-table-column
        prop="amount2"
        label="数值 2(元)">
      </el-table-column>
      <el-table-column
        prop="amount3"
        label="数值 3(元)">
      </el-table-column>
    </el-table>
  </div>
</template>
// js
data() {
      return {
        spanArr: [], // 一个空的数组,用于存放每一行记录的合并数
        pos: 0, // spanArr 的索引
        contentSpanArr: [],
        position: 0,
        data: [
          {
            id: '12987122',
            name: '王小虎',
            amount1: '234',
            amount2: '3.2',
            amount3: 10
          }, 
          {
          id: '12987122',
          name: '王小虎',
          amount1: '165',
          amount2: '4.43',
          amount3: 12
        }, 
          {
          id: '12987124',
          name: '王小虎',
          amount1: '324',
          amount2: '1.9',
          amount3: 9
        }, 
          {
          id: '12987125',
          name: '王小虎',
          amount1: '621',
          amount2: '2.2',
          amount3: 17
        },
          {
          id: '12987125',
          name: '王小虎',
          amount1: '539',
          amount2: '4.1',
          amount3: 15
        }]
      };
    },
    created(){
      this.getSpanArr(this.data)
    },
    methods: {
      getSpanArr(data) {
      // 设定一个数组spanArr/contentSpanArr来存放要合并的格数,同时还要设定一个变量pos/position来记录
        this.spanArr = [];
        this.contentSpanArr = [];
        for (var i = 0; i < data.length; i++) {
          if (i === 0) {
            this.spanArr.push(1);
            this.contentSpanArr.push(1);
            this.position = 0;
          } else {
            // 判断当前元素与上一个元素是否相同
            if (data[i].id === data[i - 1].id) {
                this.contentSpanArr[this.position] += 1;
                this.contentSpanArr.push(0);
              } else {
                this.contentSpanArr.push(1);
                this.position = i;
              }
         }
        }
      },
     objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
          const _row = this.contentSpanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      } 
    }

效果如下


图片.png
上一篇下一篇

猜你喜欢

热点阅读