Antd-Vue中Table组件实现相同内容列合并

此方法适用于表格中有多个相同列需要合并的情况!

核心函数:

/*
 @param {Object} record 当前行数据
 @param {number} index 当前行数据在当前分页数据中的下标
 @param {string} dataIndex 表格columns中设置的dataIndex属性
 @param {string} rowSpanName 表格columns中设置的rowSpanName名称
 @returns {Object} 某列需要的RowSpan数量对象
 */
const genCustomRow = (
  record: Record<string, any>,
  index: number,
  dataIndex: string,
  rowSpanName: string
) => {
  const pageStart = (pagination.current - 1) * pagination.pageSize;
  const pageEnd = pageStart + pagination.pageSize;
  // currentData 为当前分页数据
  const currentData = copyList.value.slice(pageStart, pageEnd);
  // currentIndex指针记录当前位置
  let currentIndex = 0;
  // rowSpanNum用于设置某列的rowSpan数据
  let rowSpanNum = 0;
  currentData.forEach((d, i) => {
  // 先判断下一位是否有数据,再对前后数据进行比较
    if (currentData[i + 1] && d[dataIndex] === currentData[i + 1][dataIndex]) {
      ++rowSpanNum;
    } else {
      // +1的原因是,如果有两行的某个数据相同,由于前指针的缘故,rowSpanNum只会加到1,而需要的数据为2
      currentData[currentIndex][rowSpanName] = rowSpanNum + 1;
      // 原因同上
      currentIndex = i + 1;
      // 归零,再次计算下一个重复数据
      rowSpanNum = 0;
    }
  });
  // 当前数据
  const currentRow = currentData[i];
  return { rowSpan: currentRow?.[rowSpanName] || 0 };
};

使用方式:

const columns = [
      {
        title: "名称",
        dataIndex: "name",
        customCell: (record, index) => {
          return genCustomRow(record, index,"name", "nameRowSpan");
        },
      },
      //...other columns
      // 如果有其他列需要合并,只需要修改genCustomRow函数中第三和第四个参数
    ]

注意:

一定要在Table组件的@change事件中,清除数据中所有的rowSpan数据:


const deleteRowSpanNames = ['nameRowSpan', 'ageRowSpan'];

dataSource.value.forEach(i => {
  deleteRowSpanNames.forEach(p => {
    if (p in i) {
      delete i[p];
    }
  });
});

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值