关于antdesign-vue循环表格合并单元格

344 阅读1分钟

在AntDesign中,合并单元格是一个常见操作,正常情况下我们都会在设置表头的columns中对 要操作的列进行数据整行判断合并多少单元格,最简单的例如合并某一列所有单元格为一个,此时如下设置:

columns: [ 
    {
        title: '测试列',
        dataIndex: 'test',
        key: 'test',
        customRender: ({ text, record, index }) => {
            const obj = {
                children: text,
                attrs: {},
            };
            if (index === 0) { 
                // 第一行数据开始,跨行合并的长度为数据data的长度 
                obj.attrs.rowSpan = this.dataSource.length
            }
            if (index >= 1) {
                // 从第一行往后的所有行表格均合并
                obj.attrs.rowSpan = 0;
            } 
            console.log('obj==', obj);
            return obj;
        },
    }
]

这个时候我们只要计算表格有几行,就可以进行单元格合并,如果是对一列进行相同数据合并,也只要循环计算相同的值的数量,同时后面对应length - 1的rowSpan都设置为0即可;

而现在有另一个需求,就是循环展示多个表格,每个表格的数组格式相同;

这个时候最主要的是要解决如何获取表格对应的dataSource,目前我使用的方法,是在渲染表格之后,先对整体数据源进行数据处理,例如在每个表格的每一行,都增加一个index字段,代表该表格在最外层数组下标,如下:

if (this.showList.length !== 0) {
    this.showList.forEach((item, index) => {
        this.showList[index].checkId = index;
        item.itemLines.forEach((jtem, jndex) => {
            this.showList[index].itemLines[jndex].checkId = index;
        });
    });
}

对数据进行处理之后,再进行单元格合并处理

columns: [
    {
        title: '测试列',
        dataIndex: 'test',
        key: 'test',
        customRender: ({ text, record, index }) => {
            const obj = {
                children: text,
                attrs: {},
            };
            let currentIndex = 0; 
            if (record.checkId) { 
                this.showList.forEach((item, jndex) => {
                    if (item.checkId === record.checkId) {
                        currentIndex = jndex; 
                    }
                });
            }
            if (index === 0) { 
                // 第一行数据开始,跨行合并的长度为数据data的长度
                if (record.checkId) {
                    obj.attrs.rowSpan = this.showList[currentIndex].itemLines.length;
                } else if (this.printDetail) {
                    obj.attrs.rowSpan = this.printDetail.itemLines.length; 
                } 
            } 
            if (index >= 1) { 
                // 从第一行往后的所有行表格均合并 
                obj.attrs.rowSpan = 0; 
            } 
            console.log('obj==', obj); 
            return obj; 
        }, 
    },
]