Ant Design Vue Table纵向自动合并单元格

  1. 在utils文件下创建verticalMergeCell.js文件,内容如下:

    const computeMergeCellSpan = (data, column, referenceColumn) => {
      referenceColumn = referenceColumn ? referenceColumn : column;
      data.forEach((element, index, array) => {
        if (element['merge'][column] === 0 || index === array.length - 1) {
          return;
        }
        if (element[referenceColumn] !== array[index + 1][referenceColumn]) {
          element['merge'][column] = 1;
        } else if (element[referenceColumn] === array[index + 1][referenceColumn]) {
          array[index]['merge'][column] = 2;
          array[index + 1]['merge'][column] = 0;
          let i = 1;
          while (index + 1 + i < array.length) {
            if (element[referenceColumn] === array[index + 1 + i][referenceColumn]) {
              array[index]['merge'][column]++;
              array[index + 1 + i]['merge'][column] = 0;
              i++;
            } else {
              i = array.length;
            }
          }
        }
      });
      return data;
    };
    
    const mergeCellRender = (value, record, column) => {
      const obj = {
        children: value,
        attrs: {},
      };
      obj.attrs.rowSpan = record['merge'][column];
      console.log(obj);
      return obj;
    };
    export { computeMergeCellSpan, mergeCellRender };
    
  2. 在需要引用的地方通过以下代码引入

    import { computeMergeCellSpan, mergeCellRender } from '@/utils/verticalMergeCell';
  3. 对Table的数据源进行处理,代码如下:

    1. this.data是Table的数据源,数组类型,对其中的每一个对象增加一个merge属性,类型为对象,代码如下:

      merge: {},

      加上之后的数据格式类似于: 

      this.data = [{
        columnA: '1111',
        columnB: '2222',
        columnC: '3333',
        columnD: '4444',
        merge: {},
      },{
        columnA: '1111',
        columnB: '2222',
        columnC: '3333',
        columnD: '4444',
        merge: {},
      },{
        columnA: '1111',
        columnB: '2222',
        columnC: '3333',
        columnD: '4444',
        merge: {},
      }]
    2. 调用computeMergeCellSpan方法处理数组

      this.data = computeMergeCellSpan(this.data, 'columnA');
  4. 在Table的列配置中,增加渲染函数,代码如下:

    {
       title: '名称',
       dataIndex: 'columnA',
       fixed: 'left',
       width: 80,
       customRender: (value, record) => {
          return mergeCellRender(value, record, 'columnA');
       },
    },

你可能感兴趣的:(Ant,Design,Vue,vue.js,javascript,es6,前端)