Files
heroui-vue/apps/docs/demos/table-expandable-rows.vue
T

156 lines
3.9 KiB
Vue

<script setup lang="ts">
import { ref } from "vue";
import { IconChevronRight } from "@tabler/icons-vue";
import {
Button,
Table,
type TableKey,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
type Row = {
children: Row[];
date: string;
id: string;
title: string;
type: string;
};
const data: Row[] = [
{
children: [
{
children: [
{
children: [],
date: "7/10/2025",
id: "3",
title: "周报",
type: "文件",
},
{
children: [],
date: "8/20/2025",
id: "4",
title: "预算",
type: "文件",
},
],
date: "8/2/2025",
id: "2",
title: "项目",
type: "文件夹",
},
],
date: "10/20/2025",
id: "1",
title: "文档",
type: "文件夹",
},
{
children: [
{
children: [],
date: "1/23/2026",
id: "6",
title: "图片 1",
type: "文件",
},
{
children: [],
date: "2/3/2026",
id: "7",
title: "图片 2",
type: "文件",
},
],
date: "2/3/2026",
id: "5",
title: "照片",
type: "文件夹",
},
];
const expandedKeys = ref<TableKey[]>(["1"]);
function isVisible(item: Row, depth: number, parents: string[]): boolean {
return parents.every((p) => expandedKeys.value.includes(p));
}
function renderRows(
items: Row[],
depth: number,
parents: string[],
): { item: Row; depth: number; parents: string[] }[] {
const out: { item: Row; depth: number; parents: string[] }[] = [];
for (const item of items) {
if (isVisible(item, depth, parents)) {
out.push({ item, depth, parents });
out.push(...renderRows(item.children, depth + 1, [...parents, item.id]));
}
}
return out;
}
const flatRows = () => renderRows(data, 0, []);
</script>
<template>
<Table>
<TableScrollContainer>
<TableContent
aria-label="文件"
class="min-w-[520px]"
:expanded-keys="expandedKeys"
tree-column="name"
@update:expanded-keys="(k: TableKey[]) => (expandedKeys = k)"
>
<TableHeader>
<TableColumn id="name" is-row-header>姓名</TableColumn>
<TableColumn id="type">类型</TableColumn>
<TableColumn id="date">修改日期</TableColumn>
</TableHeader>
<TableBody>
<template v-for="row in flatRows()" :key="row.item.id">
<TableRow
v-slot="{ isExpanded, toggleExpanded, isDisabled }"
:level="row.depth + 1"
:row-key="row.item.id"
:has-child-items="row.item.children.length > 0"
>
<TableCell
v-slot="{ isTreeColumn, hasChildItems: cellHasChildren }"
>
<span class="flex items-center gap-1">
<Button
v-if="cellHasChildren && isTreeColumn"
is-icon-only
aria-label="切换行"
size="sm"
variant="ghost"
:is-disabled="isDisabled"
@click="toggleExpanded"
>
<IconChevronRight
aria-hidden="true"
class="size-4 text-muted transition-transform duration-150"
:class="isExpanded ? 'rotate-90' : 'rtl:rotate-180'"
/>
</Button>
<span>{{ row.item.title }}</span>
</span>
</TableCell>
<TableCell>{{ row.item.type }}</TableCell>
<TableCell>{{ row.item.date }}</TableCell>
</TableRow>
</template>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>