场景:

我们可以看到,姓名这一列,有三个王小虎,二个王大虎,如果我们的需求是,将他们名字合并起来,统一为一格,(效果如下图),如果去实现?

首先,你需要确保姓名这一列是排序好的,这点可以让后端提前对数据数组排序,也可以自己在前端对数组排序,这会给我们的合并带来很大的方便。

我们通过下一列跟上一列的比较,存入要合并的标识,把结果传到官方的 span-method 事件。

var Main = {
  data() {
    return {
      tableData: [{
        id: '12987122',
        name: '王小虎',
        amount1: '234',
        amount2: '3.2',
        amount3: 10
      }, {
        id: '12987123',
        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: '12987126',
        name: '王大虎',
        amount1: '539',
        amount2: '4.1',
        amount3: 15
      }],
      // 合并单元格的标识
      spanArr: [],
      pos: 0,
    };
  },
  created() {
    this.getSpanArr();
  },
  methods: {
    
    getSpanArr() {
      const data = this.tableData;
      // 清空合并单元格的标识,解决页面在未初始化时出现的bug
      this.spanArr = [];
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0
        } else {
          // 判断当前元素与之前元素是否相同
          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;
          }
        }
      }
    },
    // 合并单元格
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (column.label === "姓名") {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        console.log(`rowspan:${_row} colspan:${_col}`)
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
  }
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.15.5/lib/index.js"></script>
<div id="app">
<template>
  <div>
    <el-table
      :data="tableData"
      :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>
</div>

@import url("//unpkg.com/element-ui@2.15.5/lib/theme-chalk/index.css");



腾讯云社区邀请各位技术博主加入,福利多多噢!
Last modification:August 16th, 2021 at 01:53 pm
如果觉得我的文章对你有用,请随意赞赏