1、官方给出的demo
官方demo地址
其中主要代码为:具体通过column
的customRender
属性实现
const renderContent = (value, row, index) => {
const obj = {
children: value,
attrs: {},
};
if (index === 4) {
obj.attrs.colSpan = 0;
}
return obj;
};
const columns = [
{
title: 'Name',
dataIndex: 'name',
customRender: (text, row, index) => {
if (index < 4) {
return <a href="javascript:;">{text}</a>;
}
return {
children: <a href="javascript:;">{text}</a>,
attrs: {
colSpan: 5,
},
};
},
},
{
title: 'Age',
dataIndex: 'age',
customRender: renderContent,
},
{
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;
},
},
{
title: 'Phone',
colSpan: 0,
dataIndex: 'phone',
customRender: renderContent,
},
{
title: 'Address',
dataIndex: 'address',
customRender: renderContent,
},
];
弊端:单元格内容不能实现太过复杂的内容和操作。
2、通过column的customCell属性实现
2.1 先实现单元格的合并
columns: [
{
title: "被推荐人姓名",
dataIndex: "name",
key: "name",
scopedSlots: {customRender: "name"},
width: 115,
// customCell方法用于设置单元格属性实现单元格合并。不用customRender方法的原因:不方便生成复杂的单元格元素内容(不好操作数据及方法)
customCell: (record, rowIndex) => {
if (record.desc) {
return {
attrs: {
colSpan: 5
}
}
}
return {
attrs: {
colSpan: 1
}
}
}
},
...
{
title: "申请进度",
dataIndex: "progress",
key: "progress",
scopedSlots: {customRender: "progress"},
width: 90,
customCell: setCustomCellColSpan
}
],
2.2、在html中通过slot实现自定义内容(配合 scopedSlots属性使用)
注:使用了customRender
方法后,再通过slot
实现自定义内容不会生效,所以才使用customCell
属性。
<template slot="name" slot-scope="text, row, index">
...
</template>
2.3、问题
问题:设置了colSpan
为0
的td
单元格还是会占据空间,导致表格看起来右侧留有空白,好像是空了一块。
解决方式:找到colSpan
为0
的单元格,设置样式display: none
。
.ant-table-tbody > tr > td[colspan="0"] {
display: none;
}