antd a-table想要实现如以下效果,有子级就显示展开图标,没有就不显示图标:
话不多说,直接上代码:
<template>
<a-table :columns="columns" :data-source="dataSource">
<template #bodyCell="{ column }">
<template v-if="column.key === 'operation'">
<a>Publish</a>
</template>
</template>
<template #expandIcon="{ expanded, onExpand, record }">
<button @click="(e) => onExpand(record, e)" v-if="record && record.more.length"
:class="`ant-table-row-expand-icon ${expanded ? 'ant-table-row-expand-icon-expanded' : 'ant-table-row-expand-icon-collapsed'}`"></button>
</template>
<template #expandedRowRender="{ record }">
<a-table :columns="innerColumns" :data-source="record.more" :pagination="false">
<template #bodyCell="{ column }">
<template v-if="column.key === 'state'">
<span>
<a-badge status="success" />
Finished
</span>
</template>
</template>
</a-table>
</template>
</a-table>
</template>
<script setup>
const columns = [
{ title: 'Name', dataIndex: 'name', key: 'name' },
{ title: 'Version', dataIndex: 'version', key: 'version' },
{ title: 'Upgraded', dataIndex: 'upgradeNum', key: 'upgradeNum' },
{ title: 'Date', dataIndex: 'createdAt', key: 'createdAt' },
{ title: 'Action', key: 'operation' },
];
const dataSource = [{
key: 0,
name: "Screem 1",
version: "10.3.4.5654",
upgradeNum: 500,
createdAt: "2014-12-24 23:12:00",
more: [
{
key: 6,
date: "2014-12-24 23:12:00",
name: "This is production name 1",
upgradeNum: "Upgraded: 56"
}, {
key: 7,
date: "2014-12-24 23:12:00",
name: "This is production name 2",
upgradeNum: "Upgraded: 56"
}, {
key: 8,
date: "2014-12-24 23:12:00",
name: "This is production name 3",
upgradeNum: "Upgraded: 56"
}
]
}, {
key: 1,
name: "Screem 2",
version: "10.3.4.5654",
upgradeNum: 700,
createdAt: "2014-12-24 23:12:00",
more: []
}, {
key: 2,
name: "Screem 3",
version: "10.3.4.5654",
upgradeNum: 300,
createdAt: "2014-12-24 23:12:00",
more: [
{
key: 9,
date: "2014-12-24 23:12:00",
name: "This is production name 1",
upgradeNum: "Upgraded: 56"
}
]
}];
const innerColumns = [
{ title: 'Date', dataIndex: 'date', key: 'date' },
{ title: 'Name', dataIndex: 'name', key: 'name' },
{ title: 'Upgrade Status', dataIndex: 'upgradeNum', key: 'upgradeNum' },
];
</script>
关键在于#expandIcon设置自定义图标,效果跟默认的效果一毛一样。
要注意:
我使用的是antd4,所以图标的类名是
ant-table-row-expand-icon-expanded、ant-table-row-expand-icon-collapsed。
大家如果用的版本不一样,可以控制台看下它默认渲染的图标类名是什么,直接复制过来替换掉就可以了,完美!
<template #expandIcon="{ expanded, onExpand, record }">
<button @click="(e) => onExpand(record, e)" v-if="record && record.more.length"
:class="`ant-table-row-expand-icon ${expanded ? 'ant-table-row-expand-icon-expanded' : 'ant-table-row-expand-icon-collapsed'}`"></button>
</template>