ant design vue表格合并
先看一下官方文档给出的合并单元格的方法,要合并Home phone这一列,columns中的代码如下:
{
title: 'Home phone',
colSpan: 2,
dataIndex: 'tel',
customRender: (value, row, index) => {
const obj = {
children: value,
attrs: {},
};
if (index === 2) {
obj.attrs.rowSpan = 2;
}
// These two are merged into above cell
if (index === 3) {
obj.attrs.rowSpan = 0;
}
if (index === 4) {
obj.attrs.colSpan = 0;
}
return obj;
},
},
使用 render 里的单元格属性 colSpan 或者 rowSpan 设值。
但我在应用过程中发现跟我的实际情况不太符合,一直出现问题(大概率是我代码逻辑有问题,哈哈哈),于是,我便采用了如下方法,也是参考了另一位博主的博文,记录如下:
columns: [
{
title: '日期',
align: 'center',
dataIndex: 'date',
width: 120,
sorter: true,
customRender(_, row) {
return {
children: row.date,
attrs: {
rowSpan: row.dateRowSpan,
},
};
},
},
.....
自己定义一个方法,传入要合并的列,和表格数据,进行处理
this.rowSpan("date",this.data)
rowSpan(key,data) {
let arr = data
.reduce((result, item) => {
if (result.indexOf(item[key]) < 0) {
result.push(item[key]);
}
return result;
}, [])
.reduce((result, keys) => {
const children = data.filter((item) => item[key] === keys);
result = result.concat(
children.map((item, index) => ({
...item,
[`${key}RowSpan`]: index === 0 ? children.length : 0,
}))
);
return result;
}, []);
this.dataSource = arr;
},
可以看到上面的rowSpan函数进行了两次reduce(归并),第一次是为了去重,返回一个去重的key的数组。第二次reduce是为了找出每个key重复的次数,并且将重复的次数记录在data数组中的的每个对象中,后面用于合并单元格。
效果如下: