Tree table
When your data naturally has a parent-child hierarchy, use a tree table rather than expandable rows. A tree table manages how multi-level nodes are displayed based on childrenColumnName, the indent width and the expand state.
Live demo
A three-level organization tree with controlled expansion (expandedRowKeys + onExpandedRowsChange); checking a parent node also checks its child nodes.
Basic example
<script setup lang="ts">
import { ref } from 'vue'
import {
VTable,
type Key,
type TableColumnsType,
type TableProps,
} from '@vtable-guild/vtable-guild'
interface OrgNode {
key: string
name: string
children?: OrgNode[]
}
const columns: TableColumnsType<OrgNode> = [{ title: 'Department', key: 'name', dataIndex: 'name' }]
const treeData: OrgNode[] = [
{ key: 'team', name: 'Product team', children: [{ key: 'design', name: 'Design group' }] },
]
const expandedRowKeys = ref<Key[]>(['team'])
const handleExpandedRowsChange: NonNullable<TableProps<OrgNode>['onExpandedRowsChange']> = (
keys,
) => {
expandedRowKeys.value = keys
}
</script>
<template>
<VTable
row-key="key"
:columns="columns"
:data-source="treeData"
children-column-name="children"
:indent-size="20"
:expanded-row-keys="expandedRowKeys"
@expanded-rows-change="handleExpandedRowsChange"
/>
</template>In TableProps<OrgNode>, onExpand has the signature (expanded: boolean, record: OrgNode) => void, and onExpandedRowsChange receives Key[]. When you declare a callback separately, use NonNullable<TableProps<OrgNode>['onExpandedRowsChange']> to keep the interface type and drop the undefined of the optional property.
Common controls
childrenColumnNameSets the field name of the child nodesindentSizeControls the indent width of each leveldefaultExpandedRowKeysSets the nodes expanded by defaultexpandedRowKeysSwitches to a fully controlled expand staterowSelection.checkStrictlyControls whether parent and child selection are linkedvirtualTree data can use virtual scrolling, with the expand state maintained by the component; see Virtual scrolling
When to use
- The data itself has a parent-child hierarchy, rather than attached details
- You need to handle node expansion, indentation and parent-child selection in one place
- The page has a tree structure and you still want to keep the column definitions and interactions of a regular table
Lazy loading, failure and retry
Configure loadData(record, { signal }) => Promise<TRecord[]> and isLeaf(record). The interaction keeps the expand pattern of the Ant Design tree table: after you click to expand, an inline loading state is shown; on failure the error icon stays, and clicking again retries. onTreeLoadError(error, record) can be wired to your application's message notifications.
- Concurrent loads of the same node are merged into one request; successful results are cached by the stable key and the identity of the original record.
- Collapsing does not cancel the request; the response is cached but the node is not expanded again. Controlled
expandedRowKeysare still updated by the application; nodes expanded by default are loaded too. - A node becomes a leaf after an empty array is returned. Existing children are used directly; the component does not modify the input dataSource.
- When a node is removed, a record with the same key is replaced, the loader or the children field changes, or the component unmounts, the old request is invalidated and its signal is aborted. After a record is replaced, it is loaded again when needed.
- When the application adds a children array to the same record, the application data wins and the node's old request, cache and error are cleared; removing that array does not restore the old cache. Deep children replacements in reactive data follow the same rule.
- Invalidation and unmounting immediately make pending loads / retries return
false, even if the underlying client ignores the signal. If the error notification callback itself throws or rejects asynchronously, it does not overwrite the original load error, nor does it turn the retry Promise into a rejection. - Loaded child nodes take part in parent-child selection and virtualization just like regular children; a parent node's selection state is recalculated from the child nodes loaded so far and does not mean that all descendants not yet loaded from the server are selected.
- Filtering and sorting still handle only the top level. Pagination paginates root nodes only; child nodes follow their parent.
- The instance method
retryTreeLoad(key)retries programmatically;getTreeLoadError(key)reads the error.
Known limitations
- Lazy loading needs stable keys: do not use the row index. A record that declares
children: []is treated as a leaf; a record without children is decided byisLeaf(record)and can still be loaded when it is not declared a leaf. - Filtering and sorting apply only to top-level records: the data pipeline is
dataSource → filter → sort → expand, andonFilterdoes not recurse intochildren. When a parent node matches, all of its child nodes are kept (even if the child nodes themselves do not match); when a parent node does not match, its whole subtree is removed with it (even if some child nodes match). Sorting works the same way: only root nodes are reordered, and the order among child nodes stays unchanged. To filter or sort by level, process the data in your application first and then pass it in.
API
TRecord is the application row type. See the API Reference for the full table configuration.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
rowKey | string | ((record: TRecord) => Key) | 'key' | Unique row identity. Selection state is recorded by row key, so it must be stable and unique. |
childrenColumnName | string | 'children' | Field name of the child nodes in tree data. |
indentSize | number | 15 | Indent width of tree data, in px. |
expandedRowKeys | Key[] | - | Controlled list of expanded keys for tree data. |
defaultExpandedRowKeys | Key[] | - | Default list of expanded keys for tree data. |
defaultExpandAllRows | boolean | false | Expands all nodes of tree data by default. |
onExpand | (expanded: boolean, record: TRecord) => void | - | Expand/collapse callback for tree data. |
onExpandedRowsChange | (expandedKeys: Key[]) => void | - | Callback when the expanded keys of tree data change. |
loadData | TableTreeLoadData<TRecord> | - | (record, { signal }) => Promise<TRecord[]>; lazily loads nodes that provide no children. |
isLeaf | (record: TRecord) => boolean | - | Explicitly marks the leaf nodes of a lazy tree; a node that already has children: [] also counts as a leaf. |
onTreeLoadError | (error: Error, record: TRecord) => void | - | Lazy loading error notification; can be bound with @tree-load-error. |
RowSelection
| Field | Type | Default | Description |
|---|---|---|---|
checkStrictly | boolean | true | Whether parent and child rows are selected independently in tree data. |
Theming
The expand, loading and retry styles of tree nodes can be overridden through the per-instance ui or the global theme.table.slots. To adjust colors or sizes, use the CSS variables below. See Three-layer theme overrides for the override order.
ui slots
| Slot | Description |
|---|---|
treeExpandIcon | Base styles of the tree expand button. |
treeExpandIconExpanded | Expanded state. |
treeExpandIconCollapsed | Collapsed state. |
treeExpandIconSpaced | Placeholder for leaf nodes. |
treeExpandIconDisabled | Disabled state. |
treeExpandIconSymbol | Tree symbol container. |
treeExpandIconSymbolExpanded | Tree expanded symbol state. |
treeExpandIconSymbolCollapsed | Tree collapsed symbol state. |
treeExpandIconLoading | Button state while lazy loading is in progress. |
treeExpandIconError | Retry button state after lazy loading fails. |
Preset defaults
Use the tabs below to switch between the default classes of the two presets. For how to override utilities in the default precompiled mode, see Prefix and override rules.
createVTableGuild({
theme: {
table: {
slots: {
treeExpandIcon: "relative me-2 inline-flex h-[17px] w-[17px] shrink-0 items-center justify-center origin-center scale-[0.941176] p-0 leading-[17px] rounded-[6px] border border-[color:var(--vtg-table-border-color,#d9d9d9)] bg-[color:var(--vtg-table-bg,#fff)] text-[color:var(--vtg-table-text-color)] cursor-pointer align-sub select-none transition-[border-color,background-color,color] duration-200 hover:border-[color:var(--color-primary)] hover:text-[color:var(--color-primary)] focus:border-[color:var(--color-primary)] focus:text-[color:var(--color-primary)] active:border-[color:var(--color-primary)] active:text-[color:var(--color-primary)] before:absolute before:left-[3px] before:right-[3px] before:top-[7px] before:h-px before:bg-current before:content-[''] after:absolute after:bottom-[3px] after:left-[7px] after:top-[3px] after:w-px after:origin-center after:bg-current after:content-[''] after:transition-transform after:duration-200",
treeExpandIconExpanded: 'after:scale-y-0',
treeExpandIconCollapsed: 'after:scale-y-100',
treeExpandIconSpaced: 'me-2 cursor-default border-transparent bg-transparent before:hidden after:hidden invisible',
treeExpandIconDisabled: 'me-2 cursor-default border-transparent bg-transparent before:hidden after:hidden invisible',
treeExpandIconSymbol: 'hidden',
treeExpandIconLoading: 'before:hidden after:hidden [&>span]:text-[length:12px] [&>span]:animate-spin motion-reduce:[&>span]:animate-none',
treeExpandIconError: 'before:hidden after:hidden text-[color:var(--color-error)]',
treeExpandIconSymbolExpanded: '',
treeExpandIconSymbolCollapsed: '',
},
},
},
})createVTableGuild({
themePreset: 'element-plus',
theme: {
table: {
slots: {
treeExpandIcon: 'me-1 inline-flex h-[23px] w-5 shrink-0 items-center justify-center border-0 bg-transparent p-0 text-[color:var(--vtg-table-text-color)] cursor-pointer align-middle transition-[color,transform] duration-200',
treeExpandIconExpanded: '',
treeExpandIconCollapsed: '',
treeExpandIconSpaced: 'me-1 cursor-default opacity-0',
treeExpandIconDisabled: 'me-1 cursor-not-allowed text-[color:var(--color-muted)]',
treeExpandIconSymbol: 'inline-flex items-center justify-center text-[12px] leading-none transition-transform duration-300 [&>svg]:h-[1em] [&>svg]:w-[1em]',
treeExpandIconLoading: '[&>span]:text-[length:12px] [&>span]:animate-spin motion-reduce:[&>span]:animate-none',
treeExpandIconError: 'text-[color:var(--color-error)]',
treeExpandIconSymbolExpanded: 'rotate-90',
treeExpandIconSymbolCollapsed: 'rotate-0',
},
},
},
})CSS variables
The table lists the defaults in light mode. Dark mode can be overridden separately under .dark.
| Variable | Purpose | antdv | element-plus |
|---|---|---|---|
--vtg-table-bg | Main table background, used by areas such as table and td | var(--color-surface) | var(--color-surface) |
--vtg-table-text-color | Body text color | var(--color-on-surface) | var(--color-text-regular) |
--vtg-table-border-color | Table border and cell dividers | var(--color-default) | var(--color-default) |
--color-primary | Theme primary color, used for drag handle hover, button highlights, field states and more | #1677ff | #409eff |
Type Declarations
The tree configuration belongs directly to TableProps<TRecord>, and parent-child selection belongs to RowSelection<TRecord>. The children field in a record is declared by the application type; the default field name is children. The props are an excerpt of the relevant fields; TreeFields is a documentation helper interface, not a package export. See the Type reference for the full declarations.
View type declarations
export type Key = string | number/** TableProps 节选;文档辅助接口,不是包导出。 */
export interface TreeFields<TRecord extends object = Record<string, any>> {
loadData?: TableTreeLoadData<TRecord>
isLeaf?: (record: TRecord) => boolean
onTreeLoadError?: (error: Error, record: TRecord) => void
childrenColumnName?: string
rowKey?: string | ((record: TRecord) => Key)
indentSize?: number
expandedRowKeys?: Key[]
defaultExpandedRowKeys?: Key[]
defaultExpandAllRows?: boolean
onExpand?: (expanded: boolean, record: TRecord) => void
onExpandedRowsChange?: (expandedKeys: Key[]) => void
}export interface RowSelection<TRecord extends object = Record<string, any>> {
preserveSelectedRowKeys?: boolean
type?: RowSelectionType
selectedRowKeys?: Key[]
defaultSelectedRowKeys?: Key[]
onChange?: (selectedRowKeys: Key[], selectedRows: TRecord[]) => void
onSelect?: (record: TRecord, selected: boolean, selectedRows: TRecord[]) => void
onSelectMultiple?: (selected: boolean, selectedRows: TRecord[], changeRows: TRecord[]) => void
onSelectAll?: (selected: boolean, selectedRows: TRecord[], changeRows: TRecord[]) => void
onSelectInvert?: (selectedRowKeys: Key[]) => void
onSelectNone?: () => void
getCheckboxProps?: (record: TRecord) => { disabled?: boolean; name?: string }
columnWidth?: number | string
fixed?: boolean | 'left' | 'right'
columnTitle?: string | VNodeChild
renderCell?: (
value: boolean,
record: TRecord,
index: number,
originNode: VNodeChild,
) => VNodeChild | RenderedCell
checkStrictly?: boolean
selections?: boolean | (SelectionItem | SelectionSentinel)[]
hideSelectAll?: boolean
}