返回

一个子表格只展开一行,其他行折叠:探索Ant Design Vue的便捷功能

前端

导语

在构建复杂的表格时,经常会遇到需要控制子表格展开状态的情况。例如,当多个子表格同时展开时,数据渲染可能会出现混乱,导致难以理解。为了解决这个问题,Ant Design Vue提供了@expand:expandedRowKeys属性,使您能够轻松实现只展开一行,其他行折叠的功能。

掌握Ant Design Vue的子表格展开技巧

为了使用@expand:expandedRowKeys属性,您需要按照以下步骤进行操作:

  1. 在表格组件中,使用@expand属性绑定一个方法。
  2. 在绑定的方法中,使用:expandedRowKeys属性来控制要展开的行。
  3. 当您想要展开或折叠一行时,只需更新:expandedRowKeys属性的值即可。

示例代码:

<template>
  <a-table :bordered="true" :dataSource="dataSource">
    <a-column title="姓名" dataIndex="name" key="name" />
    <a-column title="年龄" dataIndex="age" key="age" />
    <a-column title="地址" dataIndex="address" key="address" />
    <a-column
      title="操作"
      key="operation"
      @expand="handleExpand"
      :expandedRowKeys="expandedRowKeys"
    >
      <template slot-scope="record">
        <a-descriptions :bordered="true">
          <a-description label="详细地址">{record.address}</a-description>
          <a-description label="联系方式">{record.phone}</a-description>
        </a-descriptions>
      </template>
    </a-column>
  </a-table>
</template>

<script>
export default {
  data() {
    return {
      dataSource: [
        {
          key: '1',
          name: 'John Brown',
          age: 32,
          address: 'New York No. 1 Lake Park',
          phone: '0571-22098901'
        },
        {
          key: '2',
          name: 'Jim Green',
          age: 42,
          address: 'London No. 1 Lake Park',
          phone: '0571-22098902'
        },
        {
          key: '3',
          name: 'Joe Black',
          age: 32,
          address: 'Sidney No. 1 Lake Park',
          phone: '0571-22098903'
        }
      ],
      expandedRowKeys: [],
    };
  },
  methods: {
    handleExpand(expanded, record) {
      this.expandedRowKeys = expanded ? [record.key] : [];
    }
  }
};
</script>

结语

通过使用Ant Design Vue的@expand:expandedRowKeys属性,您可以轻松控制子表格的展开状态,使表格数据渲染更加清晰、易读。希望本文能帮助您掌握这一便捷的功能,并在您的项目中灵活运用。