Ant Design table 额外的展开行 expandedRowRender,实现自定义展开的icon小图标

4,160 阅读1分钟

背景

主要是实现,当表格内容较多不能一次性完全展示时,额外的展开行,自定义展开的图标显示在哪一列,自定义展开的图标

效果如下图

image.png

完整代码如下

<template>
    <a-table
        :columns="columns"
        :data-source="dataSource"
        :expandIconAsCell="false"
        :expandIconColumnIndex="2"
        :expandedRowKeys="data.expandedRowKeys"
    >
        <template #action>
            <a>Delete</a>
        </template>
        <template #expandIcon="{ record }">
            <DownSquareOutlined @click="onExpand(record)" class="expand-icon" />
        </template>
        <template #expandedRowRender="{ record }">
            <p style="margin: 0">{{ record.description }}</p>
        </template>
    </a-table>
</template>

<script lang="ts">
import { defineComponent, reactive } from 'vue'
import {DownSquareOutlined} from '@ant-design/icons-vue';
const columns = [
    { title: 'Name', dataIndex: 'name', key: 'name' },
    { title: 'Age', dataIndex: 'age', key: 'age' },
    { title: 'Address', dataIndex: 'address', key: 'address' },
    { title: 'Action', dataIndex: '', key: 'x', slots: { customRender: 'action' } },
];
const dataSource = [
    {
        index: 0,
        name: 'John Brown',
        age: 32,
        address: 'New York No. 1 Lake Park',
        description: 'My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park.',
    },
    {
        index: 1,
        name: 'Jim Green',
        age: 42,
        address: 'London No. 1 Lake Park',
        description: 'My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park.',
    },
    {
        index: 2,
        name: 'Joe Black',
        age: 32,
        address: 'Sidney No. 1 Lake Park',
        description: 'My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park.',
    },
];
interface IData {
    expandedRowKeys: any;
}

export default defineComponent({
    components: {
        DownSquareOutlined,
    },
    setup() {
        const data = reactive<IData>({
            expandedRowKeys: [],
        })
        function onExpand(record: any) {
            const set = new Set(data.expandedRowKeys);
            if (set.has(record.index)) {
                set.delete(record.index)
            } else {
                set.add(record.index)
            }
            data.expandedRowKeys = [...set]
        }
        return {
            data,
            dataSource,
            columns,
            onExpand,
        }
    },
})
</script>

补充

  • 如果想把icon放到文本后边,可以添加样式,
  • 如果想展开收缩时,切换icon图标,可以遍历数据,每条数据加一个状态,点击的时候改变一下状态

最后

文章若有不足之处,还请大家批评指出。

感谢您观看此篇文章 希望能给个👍评论收藏三连!你的点赞就是我写作的动力。