6

ElementUI表格项合并

 2 years ago
source link: https://www.xn2001.com/archives/659.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

ElementUI表格项合并

请注意,本文编写于 253 天前,最后修改于 251 天前,其中某些信息可能已经过时。

场景:

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

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

我们通过下一列跟上一列的比较,存入要合并的标识,把结果传到官方的 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')


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK