Tree
Display hierarchical data with selection, filtering, lazy loading, drag and drop, and optional virtual scrolling.
Import
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData, TreeFieldNames, TreeLoadMethod, TreeExpose } from '@nscode/handy-ui'
Basic usage
Nodes use id, label, and children by default. Each key must be unique across the tree.
<script setup lang="ts">
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
</script>
<template>
<HuiTree :data="treeData" />
</template>
Initially expanded nodes
defaultExpandAll expands the initial hierarchy. Later expansion still follows normal interaction rules.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const data = ref<TreeNodeData[]>(treeData)
const loading = ref(false)
const loadMore = () => {
loading.value = true
window.setTimeout(() => {
data.value = [
...treeData,
{
id: 4,
label: 'People',
children: [
{ id: 41, label: 'Recruiting' },
{ id: 42, label: 'Training' }
]
}
]
loading.value = false
}, 800)
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiButton :loading="loading" :disabled="data.length > 3" @click="loadMore">
Load more departments
</HuiButton>
<HuiTree :data="data" default-expand-all />
</HuiSpace>
</template>
Checkboxes
showCheckbox enables linked parent-child checking. checkedKeys supports v-model:checked-keys.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const checkedKeys = ref<(string | number)[]>([2, 111])
</script>
<template>
<HuiTree v-model:checked-keys="checkedKeys" :data="treeData" show-checkbox default-expand-all />
<p style="margin-top: 12px">Checked keys: {{ checkedKeys }}</p>
</template>
Independent checking
checkStrictly prevents a parent checkbox from changing its descendants, and vice versa.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const checkedKeys = ref<(string | number)[]>([2, 111])
</script>
<template>
<HuiTree
v-model:checked-keys="checkedKeys"
:data="treeData"
show-checkbox
check-strictly
default-expand-all
/>
<p style="margin-top: 12px">Checked keys: {{ checkedKeys }}</p>
</template>
Disabled nodes
Disabled nodes cannot be selected or checked by the user; the expansion arrow can still reveal their children.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{ id: 11, label: 'Frontend' },
{
id: 12,
label: 'Backend (disabled)',
disabled: true,
children: [
{ id: 121, label: 'Java team' },
{ id: 122, label: 'Go team' }
]
}
]
},
{ id: 3, label: 'Finance' }
]
const checkedKeys = ref<(string | number)[]>([121])
</script>
<template>
<HuiTree v-model:checked-keys="checkedKeys" :data="treeData" show-checkbox default-expand-all />
</template>
Accordion expansion
accordion permits one expanded sibling at each level without collapsing its ancestors.
<script setup lang="ts">
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
</script>
<template>
<HuiTree :data="treeData" accordion />
</template>
Current-node highlight
Use highlightCurrent with v-model:current-key. Programmatic key changes update the highlight.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const currentKey = ref<string | number | null>(21)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiButton size="small" @click="currentKey = 111">Set to “Web team”</HuiButton>
<HuiButton size="small" @click="currentKey = 3">Set to “Finance”</HuiButton>
<HuiButton size="small" @click="currentKey = null">Clear highlight</HuiButton>
</HuiSpace>
<HuiTree
v-model:current-key="currentKey"
:data="treeData"
highlight-current
default-expand-all
/>
<p>Current node key: {{ currentKey }}</p>
</HuiSpace>
</template>
Expand only with arrows
Set expandOnClickNode=false to keep text activation separate from expansion.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const clicked = ref('')
</script>
<template>
<HuiTree
:data="treeData"
:expand-on-click-node="false"
highlight-current
@node-click="clicked = String($event.node.label)"
/>
<p style="margin-top: 12px">
{{
clicked
? `Activated “${clicked}”: node-click only; no expansion`
: 'Activate node text; use the arrow to expand'
}}
</p>
</template>
Node events
Observe clicks, expansion, collapse, and checking. Event results are rendered on the page.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const events = ref<string[]>([])
const record = (text: string) => {
events.value = [text, ...events.value].slice(0, 6)
}
type NodeEvent = { node: TreeNodeData; key: string | number }
const onClick = ({ node }: NodeEvent) => record(`node-click: ${node.label}`)
const onExpand = ({ node }: NodeEvent) => record(`node-expand: ${node.label}`)
const onCollapse = ({ node }: NodeEvent) => record(`node-collapse: ${node.label}`)
const onCheck = ({ node, checkedKeys }: NodeEvent & { checkedKeys: (string | number)[] }) =>
record(`check: ${node.label}, Checked ${checkedKeys.length} items`)
const onCheckChange = ({ node, checked }: NodeEvent & { checked: boolean }) =>
record(`check-change: ${node.label} → ${checked ? 'Check' : 'Uncheck'}`)
</script>
<template>
<HuiSpace wrap align="start" :size="32">
<HuiTree
:data="treeData"
show-checkbox
@node-click="onClick"
@node-expand="onExpand"
@node-collapse="onCollapse"
@check="onCheck"
@check-change="onCheckChange"
/>
<div>
<p v-if="events.length === 0">Expand, activate, or check a node</p>
<p v-for="(text, index) in events" :key="index" style="margin: 0 0 4px">{{ text }}</p>
</div>
</HuiSpace>
</template>
Context menus
node-contextmenu supplies the original mouse event. Open a context menu without changing the current node.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTree, HuiContextMenu, HuiDropdownItem, HuiMessage } from '@nscode/handy-ui'
import type { ContextMenuExpose, TreeNodeData } from '@nscode/handy-ui'
interface NodeTarget {
node: TreeNodeData
key: string | number
}
const menu = ref<ContextMenuExpose>()
const nodes: TreeNodeData[] = [
{ id: 'team', label: 'Project files', children: [{ id: 'draft', label: 'Draft' }] },
{ id: 'archive', label: 'Read-only archive', disabled: true }
]
const target = (data: unknown) => data as NodeTarget | undefined
const show = (_command: unknown, data: unknown) => {
const selected = target(data)
if (selected) HuiMessage.info(`${selected.node.label}, key=${selected.key}`)
}
</script>
<template>
<HuiTree
:data="nodes"
default-expand-all
@node-contextmenu="({ node, key, event }) => menu?.open(event, { node, key })"
/>
<HuiContextMenu ref="menu" @command="show">
<template #default="{ data }">
<HuiDropdownItem command="view" icon="eye"
>View {{ target(data)?.node.label }}</HuiDropdownItem
>
</template>
</HuiContextMenu>
</template>
Custom field names
Map text, children, disabled, and leaf fields through props. Set node-key for identity; props.id is not supported. In development, passing props.id logs a one-time console warning.
<script setup lang="ts">
import { HuiSpace, HuiTree } from '@nscode/handy-ui'
const departments = [
{
code: 'dev',
name: 'Development',
items: [
{ code: 'fe', name: 'Frontend' },
{ code: 'be', name: 'Backend (locked)', locked: true }
]
},
{ code: 'ops', name: 'Operations' }
]
const fieldNames = { label: 'name', children: 'items', disabled: 'locked' }
const regions = [
{
regionId: 'east',
label: 'East region',
children: [
{ regionId: 'sh', label: 'Shanghai' },
{ regionId: 'hz', label: 'Hangzhou' }
]
},
{ regionId: 'south', label: 'South region' }
]
</script>
<template>
<HuiSpace wrap align="start" :size="48">
<HuiTree :data="departments" node-key="code" :props="fieldNames" default-expand-all />
<HuiTree :data="regions" node-key="regionId" default-expand-all />
</HuiSpace>
</template>
Custom node content
The default slot receives node and zero-based level. Stop propagation on embedded controls when they should not activate the node.
<script setup lang="ts">
import { HuiButton, HuiIcon, HuiMessage, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
count: 36,
children: [
{
id: 11,
label: 'Frontend',
count: 12,
children: [
{ id: 111, label: 'Web team', count: 8 },
{ id: 112, label: 'Mobile team', count: 4 }
]
},
{ id: 12, label: 'Backend', count: 24 }
]
},
{
id: 2,
label: 'Marketing',
count: 15,
children: [
{ id: 21, label: 'East region', count: 9 },
{ id: 22, label: 'South region', count: 6 }
]
},
{ id: 3, label: 'Finance', count: 5 }
]
const edit = (node: TreeNodeData) => HuiMessage.info(`Edit“${node.label}”`)
</script>
<template>
<HuiTree :data="treeData" default-expand-all style="max-width: 400px">
<template #default="{ node, level }">
<div class="node">
<HuiIcon :name="node.children ? 'folder' : 'users'" />
<span>{{ node.label }}</span>
<span class="node__meta">{{ node.count }} members · Level {{ level + 1 }} </span>
<HuiButton
size="small"
variant="text"
type="primary"
icon="edit"
aria-label="Edit"
@click.stop="edit(node)"
/>
</div>
</template>
</HuiTree>
</template>
<style scoped>
.node {
display: flex;
align-items: center;
gap: 6px;
}
.node__meta {
flex: 1;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Built-in search
filterable adds a search input. Matches retain their ancestors and descendants, expand matching branches, and highlight matched default labels.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const currentKey = ref<string | number | null>(null)
</script>
<template>
<div style="width: 280px; max-width: 100%; height: 360px">
<HuiTree
v-model:current-key="currentKey"
:data="treeData"
filterable
highlight-current
:expand-on-click-node="false"
style="height: 100%"
/>
</div>
</template>
Custom search rules
filterNodeMethod receives the trimmed keyword and node. This example also matches business codes.
<script setup lang="ts">
import { HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const departments: TreeNodeData[] = [
{
id: 1,
label: 'Development',
code: 'DEV',
children: [
{ id: 11, label: 'Frontend', code: 'FE' },
{ id: 12, label: 'Backend', code: 'BE' }
]
},
{ id: 2, label: 'Operations', code: 'OPS' }
]
const filterNodeMethod = (keyword: string, node: TreeNodeData) =>
String(node.label).includes(keyword) ||
String(node.code).toLowerCase() === keyword.toLowerCase()
</script>
<template>
<HuiTree
:data="departments"
filterable
filter-placeholder="Department name or code"
filter-empty-text="No matching departments"
:filter-node-method="filterNodeMethod"
style="max-width: 280px"
/>
</template>
External search input
Use TreeExpose.filter(keyword) to drive filtering without the built-in input.
<script setup lang="ts">
import { ref } from 'vue'
import type { TreeExpose } from '@nscode/handy-ui'
import { HuiInput, HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const treeRef = ref<TreeExpose>()
const keyword = ref('')
const onInput = (value: string | number) => {
keyword.value = String(value)
treeRef.value?.filter(keyword.value)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput
:model-value="keyword"
placeholder="Type here to filter the tree"
clearable
@update:model-value="onInput"
/>
<HuiTree ref="treeRef" :data="treeData" />
</HuiSpace>
</template>
Node filtering
filterMethod retains matching nodes with their ancestors and descendants. Clearing the filter restores visibility without removing data.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const keyword = ref('')
const filterMethod = (node: TreeNodeData) => String(node.label ?? '').includes(keyword.value)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput
v-model="keyword"
placeholder="Filter by keyword"
clearable
style="max-width: 280px"
/>
<HuiTree :data="treeData" :filter-method="keyword ? filterMethod : undefined" />
</HuiSpace>
</template>
Combining filters
When filterMethod and keyword matching are both present, each node must satisfy both predicates.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const leafOnly = ref(true)
const isLeaf = (node: TreeNodeData) => !node.children?.length
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSwitch v-model="leafOnly" active-text="Leaf nodes only (filter-method)" />
<HuiTree
:data="treeData"
filterable
:filter-method="leafOnly ? isLeaf : undefined"
style="width: 280px; max-width: 100%"
/>
</HuiSpace>
</template>
Read and set checked keys
getCheckedKeys, getHalfCheckedKeys, and setChecked expose selection through TreeExpose.
<script setup lang="ts">
import { ref } from 'vue'
import type { TreeExpose } from '@nscode/handy-ui'
import { HuiButton, HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: 'Research center',
children: [
{
id: 11,
label: 'Frontend',
children: [
{ id: 111, label: 'Web team' },
{ id: 112, label: 'Mobile team' }
]
},
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
]
const treeRef = ref<TreeExpose>()
const result = ref('')
const read = () => {
const checked = treeRef.value?.getCheckedKeys() ?? []
const halfChecked = treeRef.value?.getHalfCheckedKeys() ?? []
result.value = `Check: ${checked.join(', ') || 'None'}; Indeterminate: ${halfChecked.join(', ') || 'None'}`
}
const setChecked = (key: number, checked: boolean) => {
treeRef.value?.setChecked(key, checked)
read()
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiButton size="small" @click="setChecked(21, true)">Check“East region”</HuiButton>
<HuiButton size="small" @click="setChecked(11, true)">Check“Frontend”</HuiButton>
<HuiButton size="small" @click="setChecked(11, false)">Uncheck“Frontend”</HuiButton>
<HuiButton size="small" type="primary" @click="read">Read selection</HuiButton>
</HuiSpace>
<HuiTree ref="treeRef" :data="treeData" show-checkbox default-expand-all />
<p>{{ result || 'Use the buttons above' }}</p>
</HuiSpace>
</template>
Lazy loading
Enable lazy and return child nodes from load(node). isLeaf=true suppresses loading; an existing children array means the node is already loaded.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const provinces: TreeNodeData[] = [
{ id: 'zj', label: 'Zhejiang' },
{ id: 'js', label: 'Jiangsu' },
{ id: 'sh', label: 'Shanghai (isLeaf)', isLeaf: true }
]
const regions: Record<string, TreeNodeData[]> = {
zj: [
{ id: 'hz', label: 'Hangzhou' },
{ id: 'nb', label: 'Ningbo' }
],
js: [
{ id: 'nj', label: 'Nanjing' },
{ id: 'sz', label: 'Suzhou (no children)' }
],
hz: [
{ id: 'xh', label: 'Xihu', isLeaf: true },
{ id: 'bj', label: 'Binjiang', isLeaf: true }
],
nb: [{ id: 'hs', label: 'Haishu', isLeaf: true }],
nj: [
{ id: 'xw', label: 'Xuanwu', isLeaf: true },
{ id: 'gl', label: 'Gulou', isLeaf: true }
]
}
const logs = ref<string[]>([])
const load = (node: TreeNodeData) =>
new Promise<TreeNodeData[]>((resolve) => {
logs.value = [`Load “${node.label}” children…`, ...logs.value].slice(0, 6)
window.setTimeout(() => resolve(regions[String(node.id)] ?? []), 800)
})
</script>
<template>
<HuiSpace wrap align="start" :size="32">
<HuiTree :data="provinces" lazy :load="load" style="width: 260px" />
<div>
<p v-if="logs.length === 0" style="margin: 0">Expand a node to load its children on demand</p>
<p v-for="(text, index) in logs" :key="index" style="margin: 0 0 4px">{{ text }}</p>
</div>
</HuiSpace>
</template>
Load failures and retry
A rejected Promise emits load-error and keeps the node collapsed. Expanding again retries.
<script setup lang="ts">
import { HuiMessage, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const data: TreeNodeData[] = [
{ id: 'east', label: 'East region' },
{ id: 'south', label: 'South region (first attempt fails)' }
]
const failedOnce = new Set<string | number | undefined>()
const load = (node: TreeNodeData) =>
new Promise<TreeNodeData[]>((resolve, reject) => {
window.setTimeout(() => {
if (node.id === 'south' && !failedOnce.has(node.id)) {
failedOnce.add(node.id)
reject(new Error('Network timeout'))
return
}
resolve(
[1, 2, 3].map((i) => ({ id: `${node.id}-${i}`, label: `Branch ${i}`, isLeaf: true }))
)
}, 800)
})
const onLoadError = ({ node, error }: { node: TreeNodeData; error: unknown }) => {
HuiMessage.error(
`“${node.label}”Loading failed: ${(error as Error).message}, expand again to retry`
)
}
</script>
<template>
<HuiTree :data="data" lazy :load="load" style="max-width: 320px" @load-error="onLoadError" />
</template>
Loading with checks and search
Loaded children join existing check propagation and filter calculations. Map isLeaf when the backend uses another field.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const data: TreeNodeData[] = [
{ id: 'dev', name: 'Research center', leaf: false },
{ id: 'market', name: 'Marketing', leaf: false },
{ id: 'finance', name: 'Finance', leaf: true }
]
const departments: Record<string, TreeNodeData[]> = {
dev: [
{ id: 'fe', name: 'Frontend', leaf: false },
{ id: 'be', name: 'Backend', leaf: true }
],
fe: [
{ id: 'web', name: 'Web team', leaf: true },
{ id: 'app', name: 'Mobile team', leaf: true }
],
market: [
{ id: 'east', name: 'East region', leaf: true },
{ id: 'south', name: 'South region', leaf: true }
]
}
const fieldNames = { label: 'name', isLeaf: 'leaf' }
const load = (node: TreeNodeData) =>
new Promise<TreeNodeData[]>((resolve) => {
window.setTimeout(() => resolve(departments[String(node.id)] ?? []), 600)
})
const checkedKeys = ref<(string | number)[]>(['dev'])
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiTree
v-model:checked-keys="checkedKeys"
:data="data"
:props="fieldNames"
lazy
:load="load"
show-checkbox
filterable
style="width: 280px; max-width: 100%"
/>
<p style="margin: 0">Checked keys: {{ checkedKeys }}</p>
</HuiSpace>
</template>
Drag and drop
draggable moves nodes in the supplied data. Keep that data editable and reactive when other views need to follow changes.
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiMessage, HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeDropData, TreeNodeData } from '@nscode/handy-ui'
const data = ref<TreeNodeData[]>([
{
id: 1,
label: 'Research center',
children: [
{ id: 11, label: 'Frontend' },
{ id: 12, label: 'Backend' }
]
},
{
id: 2,
label: 'Marketing',
children: [
{ id: 21, label: 'East region' },
{ id: 22, label: 'South region' }
]
},
{ id: 3, label: 'Finance' }
])
const outline = (nodes: TreeNodeData[], depth = 0): string[] =>
nodes.flatMap((node) => [
`${' '.repeat(depth)}${node.label}`,
...outline(node.children ?? [], depth + 1)
])
const structure = computed(() => outline(data.value).join('\n'))
const positions = { before: 'before', after: 'after', inner: 'inside' }
const onDrop = ({ draggingNode, dropNode, dropType }: TreeDropData) => {
HuiMessage.success(
`“${draggingNode.label}”dropped at “${dropNode.label}”${positions[dropType]}`
)
}
</script>
<template>
<HuiSpace wrap align="start" :size="32">
<HuiTree :data="data" draggable default-expand-all style="width: 240px" @node-drop="onDrop" />
<pre style="margin: 0; line-height: 1.8">{{ structure }}</pre>
</HuiSpace>
</template>
Restrict dragging and dropping
allowDrag controls the dragged node. allowDrop separately evaluates before, after, and inner placement; disabled destinations cannot accept inner drops; their expansion controls still work.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiIcon, HuiTree } from '@nscode/handy-ui'
import type { TreeDropType, TreeNodeData } from '@nscode/handy-ui'
const data = ref<TreeNodeData[]>([
{
id: 'project',
label: 'Projects',
type: 'folder',
children: [
{
id: 'src',
label: 'src',
type: 'folder',
children: [
{ id: 'main', label: 'main.ts', type: 'file' },
{ id: 'app', label: 'App.vue', type: 'file' }
]
},
{ id: 'public', label: 'public', type: 'folder', children: [] },
{ id: 'pkg', label: 'package.json', type: 'file' },
{ id: 'readme', label: 'README.md', type: 'file' }
]
}
])
const allowDrag = (node: TreeNodeData) => node.id !== 'project'
const allowDrop = (_dragging: TreeNodeData, drop: TreeNodeData, type: TreeDropType) => {
if (type === 'inner') return drop.type === 'folder'
return drop.id !== 'project'
}
</script>
<template>
<HuiTree
:data="data"
draggable
default-expand-all
:allow-drag="allowDrag"
:allow-drop="allowDrop"
style="max-width: 320px"
>
<template #default="{ node }">
<span class="file-node">
<HuiIcon :name="node.type === 'folder' ? 'folder' : 'file'" />
{{ node.label }}
</span>
</template>
</HuiTree>
</template>
<style scoped>
.file-node {
display: inline-flex;
align-items: center;
gap: 6px;
}
</style>
Drag events
Drag events describe source, destination, placement, and original event. node-drag-end fires before node-drop; cancellation has no destination.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTree } from '@nscode/handy-ui'
import type {
TreeDragData,
TreeDragEndData,
TreeDragOverData,
TreeDropData,
TreeNodeData
} from '@nscode/handy-ui'
const data = ref<TreeNodeData[]>([
{
id: 1,
label: 'Research center',
children: [
{ id: 11, label: 'Frontend' },
{ id: 12, label: 'Backend' }
]
},
{ id: 2, label: 'Marketing' },
{ id: 3, label: 'Finance' }
])
const positions = { before: 'before', after: 'after', inner: 'inside' }
const events = ref<string[]>([])
const record = (text: string) => {
events.value = [text, ...events.value].slice(0, 8)
}
const over = ref('')
const onStart = ({ node }: { node: TreeNodeData }) => {
events.value = []
record(`node-drag-start: ${node.label}`)
}
const onEnter = ({ dropNode }: TreeDragData) => record(`node-drag-enter: ${dropNode.label}`)
const onLeave = ({ dropNode }: TreeDragData) => record(`node-drag-leave: ${dropNode.label}`)
const onOver = ({ dropNode, dropType }: TreeDragOverData) => {
over.value = `${dropNode.label} ${dropType ? positions[dropType] : ' (not allowed)'}`
}
const onEnd = ({ dropNode, dropType }: TreeDragEndData) => {
over.value = ''
record(
dropNode && dropType
? `node-drag-end: drop at “${dropNode.label}”${positions[dropType]}`
: 'node-drag-end: cancelled'
)
}
const onDrop = ({ draggingNode, dropNode }: TreeDropData) =>
record(`node-drop: ${draggingNode.label} → ${dropNode.label}`)
</script>
<template>
<HuiSpace wrap align="start" :size="32">
<HuiTree
:data="data"
draggable
default-expand-all
style="width: 220px"
@node-drag-start="onStart"
@node-drag-enter="onEnter"
@node-drag-leave="onLeave"
@node-drag-over="onOver"
@node-drag-end="onEnd"
@node-drop="onDrop"
/>
<div>
<p style="margin: 0 0 8px">node-drag-over: {{ over || '-' }}</p>
<p v-if="events.length === 0" style="margin: 0">Drag a node to see events</p>
<p v-for="(text, index) in events" :key="index" style="margin: 0 0 4px">{{ text }}</p>
</div>
</HuiSpace>
</template>
Virtual scrolling
virtualScroll renders a window of uniformly sized rows. Set height and itemSize to match the intended row geometry.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSegmented, HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const data: TreeNodeData[] = Array.from({ length: 100 }, (_, i) => ({
id: `d${i + 1}`,
label: `Department ${i + 1}`,
children: Array.from({ length: 100 }, (_, j) => ({
id: `d${i + 1}-${j + 1}`,
label: `Department ${i + 1} / Team ${j + 1}`
}))
}))
const itemSize = ref(32)
const sizeOptions = [
{ label: 'Row height 32', value: 32 },
{ label: 'Row height 40', value: 40 }
]
const checkedKeys = ref<(string | number)[]>([])
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSegmented v-model="itemSize" :options="sizeOptions" />
<HuiTree
v-model:checked-keys="checkedKeys"
:data="data"
virtual-scroll
:height="360"
:item-size="itemSize"
show-checkbox
filterable
default-expand-all
style="width: 320px; max-width: 100%"
/>
<p style="margin: 0">Total: 10100 nodes, Checked {{ checkedKeys.length }} items</p>
</HuiSpace>
</template>
Empty states and disabled expansion
Use emptyText or the empty slot for empty data. Disabled roots can still be expanded with the arrow.
<script setup lang="ts">
import { HuiTree, HuiSpace } from '@nscode/handy-ui'
const data = [
{
id: 'parent',
label: 'Disabled root; arrow can still expand',
disabled: true,
children: [{ id: 'child', label: 'Child node' }]
}
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTree :data="[]" empty-text="No members" />
<HuiTree :data="[]"><template #empty>Create a group first</template></HuiTree>
<HuiTree :data="data" />
</HuiSpace>
</template>
Keyboard navigation
Missing node keys (undefined or null) receive an instance-local fallback based on the original object identity, with one development warning per object. Reordering, filtering, reusing the same object, and switching between regular and virtual rendering preserve that identity without writing to the data. New objects or tree instances receive new fallbacks. Always provide a real node-key for persistence or data loaded again. Real keys retain their type: 1, '1', 0, and '' stay distinct where applicable.
Do not copy fallback keys into real business identifiers. If a later real key collides, internal expansion, checks, and current-node state move to a new fallback, with update requests only. While a parent retains the old key, that binding still refers to the original object and cannot select the new real node. Its checkbox is temporarily disabled, and its subtree is excluded from checking an ancestor through interaction, public methods, or externally checked parent nodes. Acknowledging the new key, or clearing the old binding before selecting the real key, removes this ambiguity guard. Repeating one object on multiple paths keeps both paths and one shared identity, with a development warning; independent nodes require independent objects and unique real keys.
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="nodes = [...nodes].reverse()">Reverse the same objects</HuiButton>
<HuiTree
:data="nodes"
show-checkbox
check-strictly
default-expand-all
:expand-on-click-node="false"
@node-click="current = JSON.stringify({ label: $event.node.label, key: $event.key })"
@update:checked-keys="checked = $event"
/>
<span>{{ current }}; checked keys: {{ checked }}</span>
</HuiSpace>
</template>
<script setup>
import { ref } from 'vue'
import { HuiTree, HuiButton, HuiSpace } from '@nscode/handy-ui'
const nodes = ref([
{ label: 'First without id', children: [{ label: 'Child' }] },
{ label: 'Second without id' }
])
const current = ref('No activation yet')
const checked = ref([])
</script>
The whole tree has one Tab stop. Initially it prefers the first visible enabled node; an entirely disabled tree still has a stop. The stop then follows focus, including disabled nodes. Stable node keys preserve it across reordering; a removed node yields to a nearby visible node. Data updates do not move actual focus. Up and Down stop at the boundaries. A filterable tree has a separate search input before this stop; ArrowDown in that input enters the tree.
| Key | Action |
|---|---|
| ArrowDown / ArrowUp | Focus the next / previous visible node. |
| Home / End | Focus the first / last visible node. |
| PageDown / PageUp | Move one viewport of rows, or 10 rows when measurement is unavailable, without wrapping. |
| Characters | Match a label prefix; characters within 500ms form a word, and repeated characters cycle through matches. |
| ArrowRight | Expand a collapsed node; otherwise focus its first child. |
| ArrowLeft | Collapse an expanded node; otherwise focus its parent. |
| Enter | Activate the node. |
| Space | Toggle its checkbox when present; otherwise activate the node. |
ArrowRight also starts lazy loading. Virtual scrolling preserves these controls and scrolls an off-screen destination into view.
Disabled nodes can expand, collapse, and expose their children, but Enter and Space cannot select or check them. Composition events, key code 229, Ctrl/Meta/Alt shortcuts, and already prevented events are ignored. Home/End and PageUp/PageDown in the search input retain their native text editing behavior.
Switch between regular and virtual rendering below. Press B to focus the disabled Bravo node and ArrowRight to reach its child. Navigation alone does not activate a node.
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="virtual = !virtual"
>Virtual scrolling: {{ virtual ? 'on' : 'off' }}</HuiButton
>
<HuiTree
:data="data"
:virtual-scroll="virtual"
:height="160"
show-checkbox
default-expand-all
@node-click="last = String($event.key)"
/>
<span>Last activation: {{ last }}</span>
</HuiSpace>
</template>
<script setup>
import { ref } from 'vue'
import { HuiTree, HuiButton, HuiSpace } from '@nscode/handy-ui'
const virtual = ref(false)
const last = ref('None')
const data = [
{ id: 'alpha', label: 'Alpha' },
{ id: 'bravo', label: 'Bravo', disabled: true, children: [{ id: 'child', label: 'Child' }] },
...Array.from({ length: 18 }, (_, index) => ({ id: index, label: `Item ${index + 1}` }))
]
</script>
Form isolation
Search and built-in node checkboxes ignore the outer Form disabled/readonly state, label registration, and validation. A node's own disabled flag still applies. Node and empty slots retain their context, so these business inputs remain disabled and label-associated. Search and standalone tree checkbox sizes remain default.
<script setup lang="ts">
import { HuiForm, HuiFormItem, HuiInput, HuiTree } from '@nscode/handy-ui'
const boundaryData = [
{ id: 1, label: 'Browsable node' },
{ id: 2, label: 'Disabled node', disabled: true }
]
</script>
<template>
<HuiForm disabled size="large">
<HuiFormItem label="Node business value">
<HuiTree :data="boundaryData" show-checkbox filterable>
<template #default="{ node }"><HuiInput :model-value="node.label" @click.stop /></template>
</HuiTree>
</HuiFormItem>
</HuiForm>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| data | TreeNodeData[] | Required | Root nodes. |
| props | TreeFieldNames | {} | Map label, children, disabled, and isLeaf fields. |
| nodeKey | string | 'id' | Unique key field. This is the only key-field setting; props.id is no longer supported. |
| defaultExpandAll | boolean | false | Initially expand every expandable node. |
| expandOnClickNode | boolean | true | Clicking a node toggles expansion. Disable it to expand only with the arrow. |
| accordion | boolean | false | Expand at most one sibling at each level. |
| highlightCurrent | boolean | false | Highlight the current node. |
| currentKey / v-model:current-key | string | number | null | — | Current node key. Requires highlightCurrent to show a highlight. |
| showCheckbox | boolean | false | Render node checkboxes. |
| checkStrictly | boolean | false | Check parents and children independently. |
| checkedKeys / v-model:checked-keys | (string | number)[] | — | Checked node keys. |
| emptyText | string | Locale No data | Empty-state text. |
| filterMethod | (node: TreeNodeData) => boolean | — | Keep matching nodes, their ancestors, and their descendants. |
| filterable | boolean | false | Show the built-in search input. |
| filterPlaceholder | string | Locale placeholder | Search input placeholder and accessible label. |
| filterNodeMethod | (keyword: string, node: TreeNodeData) => boolean | — | Custom keyword matching. Receives a trimmed, case-preserved keyword. |
| filterEmptyText | string | Locale No matches | Message when a filterable tree has no matching nodes. |
| lazy | boolean | false | Load children on the first expansion. |
| load | TreeLoadMethod | — | Required for lazy loading; returns a Promise of children. |
| draggable | boolean | false | Enable native drag and drop within this tree. |
| allowDrag | (node: TreeNodeData) => boolean | — | Decide whether a node can be dragged. Disabled nodes never can. |
| allowDrop | (draggingNode: TreeNodeData, dropNode: TreeNodeData, type: TreeDropType) => boolean | — | Permit or reject a destination and placement. |
| virtualScroll | boolean | false | Render only visible rows. |
| height | number | string | Virtual: 300 | Scrollable height. Numbers are pixels; percentages require a parent with a definite height. |
| itemSize | number | 32 | Uniform virtual row height in pixels. |
Events
Event declarations use camelCase; templates use kebab-case listeners as shown below.
| Event | Arguments | Description |
|---|---|---|
| node-click | { node: TreeNodeData; key: string | number } | Enabled node content activated. Arrows and checkboxes do not trigger it. |
| node-contextmenu | { node: TreeNodeData; key: string | number; event: MouseEvent } | Right-click node content, including disabled nodes; selection and native context behavior are unchanged. |
| node-expand | { node: TreeNodeData; key: string | number } | Node expanded, after a successful lazy load when needed. |
| node-collapse | { node: TreeNodeData; key: string | number } | Node collapsed. |
| check | { checkedKeys: (string | number)[]; node: TreeNodeData; key: string | number } | User changed a checkbox; checkedKeys is the complete resulting set. |
| check-change | { node: TreeNodeData; checked: boolean; key: string | number } | Changed node and its new check state. |
| update:checkedKeys | (keys: (string | number)[]) | Checked keys updated. |
| update:currentKey | (key: string | number | null) | Current node updated. |
| load-error | { node: TreeNodeData; key: string | number; error: unknown } | Loader rejected or threw; node remains collapsed. |
| node-drag-start | { node: TreeNodeData; key: string | number; event: DragEvent } | Drag started. |
| node-drag-enter | TreeDragData | Pointer entered a drag destination. |
| node-drag-leave | TreeDragData | Pointer left a destination or the tree. |
| node-drag-over | TreeDragOverData | Pointer moved over a destination; null dropType means the drop is disallowed. |
| node-drag-end | TreeDragEndData | Drag ended, including cancellation; emitted before node-drop. |
| node-drop | TreeDropData | Drop completed and data has already been moved. |
Slots
| Slot | Scope | Description |
|---|---|---|
| default | { node: TreeNodeData; level: number } | Custom node content; replaces the mapped label. |
| empty | — | Empty-state content, preferred over emptyText. |
Methods
Use a component ref typed as TreeExpose.
| Method | Signature | Description |
|---|---|---|
| getCheckedKeys | () => (string | number)[] | Return checked keys. |
| getHalfCheckedKeys | () => (string | number)[] | Return indeterminate keys. |
| setChecked | (key: string | number, checked: boolean) => void | Set a node's check state with the same parent-child rules as a checkbox; disabled nodes can be set programmatically. |
| filter | (keyword?: string) => void | Apply keyword filtering, updating the built-in input when shown. Empty or omitted keyword clears it. Also works without filterable. |
Types
interface TreeNodeData {
id?: string | number
label?: string
children?: TreeNodeData[]
disabled?: boolean
isLeaf?: boolean
[key: string]: unknown
}
interface TreeFieldNames {
label?: string
children?: string
disabled?: string
isLeaf?: string
}
type TreeLoadMethod = (node: TreeNodeData) => Promise<TreeNodeData[]>
type TreeDropType = 'before' | 'after' | 'inner'
interface TreeDragData {
draggingNode: TreeNodeData
draggingKey: string | number
dropNode: TreeNodeData
dropKey: string | number
event: DragEvent
}
interface TreeDragOverData extends TreeDragData {
dropType: TreeDropType | null
}
interface TreeDropData extends TreeDragData {
dropType: TreeDropType
}
interface TreeDragEndData {
draggingNode: TreeNodeData
draggingKey: string | number
dropNode: TreeNodeData | null
dropKey: string | number | null
dropType: TreeDropType | null
event: DragEvent
}
interface TreeExpose {
getCheckedKeys: () => (string | number)[]
getHalfCheckedKeys: () => (string | number)[]
setChecked: (key: string | number, checked: boolean) => void
filter: (keyword?: string) => void
}
The old FieldNames type remains a deprecated alias of TreeFieldNames until 1.0. This type alias does not restore the removed props.id setting. TreeEmits uses camelCase event names, including nodeClick, checkChange, loadError, and nodeDragStart.