Tree 树形控件
用树形结构展示有层级关系的数据,节点可以展开、收起、勾选。常用在目录、组织架构、权限配置这类场景。
引入
import { NsTree } from '@ns/ui'
基础用法
data 传树形数据,每个节点要有唯一的 id,label 是节点文字,children 是子节点。默认全部收起,点节点或者节点前面的箭头展开。
<script setup lang="ts">
import { NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
</script>
<template>
<NsTree :data="treeData" />
</template>
默认展开
加上 default-expand-all 后一开始就展开所有节点。数据是后来才加载的时候,新出现的节点同样会展开:点“加载更多部门”,0.8 秒后替换成新数据,新加的“人事部”也是展开的。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
const data = ref<TreeNodeData[]>(treeData)
const loading = ref(false)
const loadMore = () => {
loading.value = true
window.setTimeout(() => {
data.value = [
...treeData,
{
id: 4,
label: '人事部',
children: [
{ id: 41, label: '招聘组' },
{ id: 42, label: '培训组' }
]
}
]
loading.value = false
}, 800)
}
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsButton :loading="loading" :disabled="data.length > 3" @click="loadMore">
加载更多部门
</NsButton>
<NsTree :data="data" default-expand-all />
</NsSpace>
</template>
复选框
加上 show-checkbox 后每个节点前面有复选框,用 v-model:checked-keys 绑定勾选的节点 key。
默认父子关联:勾选父节点会同时勾选它下面所有没禁用的节点;子节点全部勾选后父节点自动勾选,只勾了一部分时父节点显示半选。绑定值里既有父节点也有子节点的 key,半选的父节点不在里面。
<script setup lang="ts">
import { ref } from 'vue'
import { NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
// 传父节点的 key 等于勾选它下面的所有节点:2 是“市场部”,111 是“Web 小组”
const checkedKeys = ref<(string | number)[]>([2, 111])
</script>
<template>
<NsTree v-model:checked-keys="checkedKeys" :data="treeData" show-checkbox default-expand-all />
<p style="margin-top: 12px">勾选的 key:{{ checkedKeys }}</p>
</template>
父子不关联
加上 check-strictly 后每个节点单独勾选,互不影响,也没有半选状态。
<script setup lang="ts">
import { ref } from 'vue'
import { NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
// 只勾选“市场部”本身,它下面的节点不跟着勾选;“研发中心”也不会因为“Web 小组”变成半选
const checkedKeys = ref<(string | number)[]>([2, 111])
</script>
<template>
<NsTree
v-model:checked-keys="checkedKeys"
:data="treeData"
show-checkbox
check-strictly
default-expand-all
/>
<p style="margin-top: 12px">勾选的 key:{{ checkedKeys }}</p>
</template>
禁用节点
节点数据里的 disabled: true 禁用这个节点:不能点击、不能展开或收起、不能勾选,文字显示成禁用色。勾选它的父节点时,它和它下面的节点保持原样。
下面“后端组”被禁用,它下面的“Java 小组”已经勾选。勾选“研发中心”时“后端组”和“Go 小组”不会被勾上,“研发中心”最多是半选:
<script setup lang="ts">
import { ref } from 'vue'
import { NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{ id: 11, label: '前端组' },
{
id: 12,
label: '后端组(禁用)',
disabled: true,
children: [
{ id: 121, label: 'Java 小组' },
{ id: 122, label: 'Go 小组' }
]
}
]
},
{ id: 3, label: '财务部' }
]
const checkedKeys = ref<(string | number)[]>([121])
</script>
<template>
<NsTree v-model:checked-keys="checkedKeys" :data="treeData" show-checkbox default-expand-all />
</template>
手风琴模式
加上 accordion 后,同一层里每次只展开一个节点,展开另一个时原来展开的自动收起。不同层之间互不影响。
<script setup lang="ts">
import { NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
</script>
<template>
<NsTree :data="treeData" accordion />
</template>
高亮当前节点
加上 highlight-current 后,点过的节点会高亮。用 v-model:current-key 可以读取或者设置当前节点。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
const currentKey = ref<string | number | null>(21)
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<NsButton size="small" @click="currentKey = 111">设为“Web 小组”</NsButton>
<NsButton size="small" @click="currentKey = 3">设为“财务部”</NsButton>
<NsButton size="small" @click="currentKey = null">取消高亮</NsButton>
</NsSpace>
<NsTree
v-model:current-key="currentKey"
:data="treeData"
highlight-current
default-expand-all
/>
<p>当前节点的 key:{{ currentKey }}</p>
</NsSpace>
</template>
只点箭头展开
默认点节点的任意位置都会展开或收起。:expand-on-click-node="false" 时只有点箭头才展开,点节点文字只触发 node-click(以及高亮)。
<script setup lang="ts">
import { ref } from 'vue'
import { NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
const clicked = ref('')
</script>
<template>
<NsTree
:data="treeData"
:expand-on-click-node="false"
highlight-current
@node-click="clicked = String($event.node.label)"
/>
<p style="margin-top: 12px">
{{ clicked ? `点了“${clicked}”:只触发 node-click,不展开` : '点节点文字试试,再点箭头展开' }}
</p>
</template>
节点事件
展开、收起、点击、勾选都会触发事件,参数里有节点数据 node 和它的 key。下面把最近的几次事件列出来:
node-click:点节点时触发。点箭头、点复选框、点禁用的节点不触发。node-expand、node-collapse:展开、收起时触发。check:勾选或取消勾选时触发,checkedKeys是操作后全部勾选的 key。check-change:同上,checked是被操作节点的新状态。
<script setup lang="ts">
import { ref } from 'vue'
import { NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
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},勾选了 ${checkedKeys.length} 个`)
const onCheckChange = ({ node, checked }: NodeEvent & { checked: boolean }) =>
record(`check-change:${node.label} → ${checked ? '勾选' : '取消'}`)
</script>
<template>
<NsSpace wrap align="start" :size="32">
<NsTree
: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">展开、点击、勾选节点试试</p>
<p v-for="(text, index) in events" :key="index" style="margin: 0 0 4px">{{ text }}</p>
</div>
</NsSpace>
</template>
自定义字段名
数据里的字段名不是 id、label、children、disabled 时,用 props 指定对应的字段名。只需要改 key 的字段名时也可以用 node-key。
<script setup lang="ts">
import { NsSpace, NsTree } from '@ns/ui'
// 字段名全都不一样:用 props 一一对应
const departments = [
{
code: 'dev',
name: '研发部',
items: [
{ code: 'fe', name: '前端组' },
{ code: 'be', name: '后端组(locked)', locked: true }
]
},
{ code: 'ops', name: '运维部' }
]
const fieldNames = { id: 'code', label: 'name', children: 'items', disabled: 'locked' }
// 只有 key 的字段名不一样:用 node-key
const regions = [
{
regionId: 'east',
label: '华东大区',
children: [
{ regionId: 'sh', label: '上海' },
{ regionId: 'hz', label: '杭州' }
]
},
{ regionId: 'south', label: '华南大区' }
]
</script>
<template>
<NsSpace wrap align="start" :size="48">
<NsTree :data="departments" :props="fieldNames" default-expand-all />
<NsTree :data="regions" node-key="regionId" default-expand-all />
</NsSpace>
</template>
自定义节点内容
默认插槽可以自定义每个节点的显示内容,参数是节点数据 node 和层级 level(第一层是 0)。插槽内容占满节点这一行剩下的宽度,可以把操作按钮放在最右边;按钮的点击事件加 .stop,免得同时触发节点的展开和 node-click。
<script setup lang="ts">
import { NsButton, NsIcon, NsMessage, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
count: 36,
children: [
{
id: 11,
label: '前端组',
count: 12,
children: [
{ id: 111, label: 'Web 小组', count: 8 },
{ id: 112, label: '移动端小组', count: 4 }
]
},
{ id: 12, label: '后端组', count: 24 }
]
},
{
id: 2,
label: '市场部',
count: 15,
children: [
{ id: 21, label: '华东大区', count: 9 },
{ id: 22, label: '华南大区', count: 6 }
]
},
{ id: 3, label: '财务部', count: 5 }
]
const edit = (node: TreeNodeData) => NsMessage.info(`编辑“${node.label}”`)
</script>
<template>
<NsTree :data="treeData" default-expand-all style="max-width: 400px">
<template #default="{ node, level }">
<div class="node">
<NsIcon :name="node.children ? 'folder' : 'users'" />
<span>{{ node.label }}</span>
<span class="node__meta">{{ node.count }} 人 · 第 {{ level + 1 }} 层</span>
<NsButton
size="small"
variant="text"
type="primary"
icon="edit"
aria-label="编辑"
@click.stop="edit(node)"
/>
</div>
</template>
</NsTree>
</template>
<style scoped>
.node {
display: flex;
align-items: center;
gap: 6px;
}
.node__meta {
flex: 1;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
搜索框
加上 filterable 后树的上方有一个搜索框(带搜索图标、可清空),输入关键字就过滤节点:
- 默认按节点文字(
props.label指定的字段)包含关键字过滤,不分大小写;关键字会先去掉首尾空格,只有空格时不过滤。 - 命中的节点、它的各级父节点和它下面的节点会显示,其余隐藏;为了露出命中的节点,父节点会自动展开。
- 节点文字里和关键字相同的部分用主色加粗显示(
ns-tree__highlight)。 - 清空关键字后显示全部节点,展开状态恢复成开始搜索之前的样子。
- 一个节点都没命中时显示“无匹配数据”,可以用
filter-empty-text改。
搜索框宽度撑满、和树之间隔 8px。给组件设了高度时(例如 style="height: 100%"),搜索框固定在上面,只有树在下面滚动,适合列表页左侧的树面板。试试输入“组”“大区”或“web”:
<script setup lang="ts">
import { ref } from 'vue'
import { NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
const currentKey = ref<string | number | null>(null)
</script>
<template>
<div style="width: 280px; max-width: 100%; height: 360px">
<NsTree
v-model:current-key="currentKey"
:data="treeData"
filterable
highlight-current
:expand-on-click-node="false"
style="height: 100%"
/>
</div>
</template>
在搜索框里按 ↓ 焦点进入树,之后用方向键选节点(见“键盘操作”)。
自定义搜索规则
filter-node-method 自己判断节点是否命中,参数是关键字(已去掉首尾空格,大小写不变)和节点数据。filter-placeholder 改搜索框的占位文字,filter-empty-text 改没命中时的提示。下面按名称或编码都能搜到,试试输入 fe 或“运维”,再输入一个不存在的词:
<script setup lang="ts">
import { NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const departments: TreeNodeData[] = [
{
id: 1,
label: '研发部',
code: 'DEV',
children: [
{ id: 11, label: '前端组', code: 'FE' },
{ id: 12, label: '后端组', code: 'BE' }
]
},
{ id: 2, label: '运维部', code: 'OPS' }
]
const filterNodeMethod = (keyword: string, node: TreeNodeData) =>
String(node.label).includes(keyword) ||
String(node.code).toLowerCase() === keyword.toLowerCase()
</script>
<template>
<NsTree
:data="departments"
filterable
filter-placeholder="输入部门名称或编码"
filter-empty-text="没有找到部门"
:filter-node-method="filterNodeMethod"
style="max-width: 280px"
/>
</template>
高亮只看节点文字里有没有关键字,按编码命中的节点不会有高亮。
外部输入框驱动
搜索框要放在别的地方(例如页面顶部的工具栏)时,不开 filterable,通过 ref 调用 filter(keyword)。效果和在内置搜索框里输入一样,同样会高亮、恢复展开状态;filter('') 或 filter() 取消过滤。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
const treeRef = ref<InstanceType<typeof NsTree>>()
const keyword = ref('')
const onInput = (value: string | number) => {
keyword.value = String(value)
treeRef.value?.filter(keyword.value)
}
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput
:model-value="keyword"
placeholder="在这里输入,过滤下面的树"
clearable
@update:model-value="onInput"
/>
<NsTree ref="treeRef" :data="treeData" />
</NsSpace>
</template>
节点过滤
filter-method 接收节点数据,返回 true 表示命中。命中的节点、它的各级父节点和它下面的节点会显示,其余隐藏;为了露出命中的节点,父节点会自动展开。不传(或者传 undefined)时不过滤,展开状态恢复成过滤前的样子。
下面的例子用 filter-method 自己维护关键字,和上面的写法效果相近,但不会高亮。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
const keyword = ref('')
const filterMethod = (node: TreeNodeData) => String(node.label ?? '').includes(keyword.value)
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput v-model="keyword" placeholder="输入关键字过滤" clearable style="max-width: 280px" />
<NsTree :data="treeData" :filter-method="keyword ? filterMethod : undefined" />
</NsSpace>
</template>
filter-method 和搜索关键字可以一起用:两个条件都满足的节点才算命中。例如 filter-method 只留某一类节点,搜索框在这类节点里找。下面开关打开时,filter-method 只留没有子节点的叶子节点(如“Web 小组”“后端组”“财务部”),这时在搜索框里输入“华”,只剩两个大区;关掉开关后搜索范围是全部节点:
<script setup lang="ts">
import { ref } from 'vue'
import { NsSpace, NsSwitch, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
const leafOnly = ref(true)
const isLeaf = (node: TreeNodeData) => !node.children?.length
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSwitch v-model="leafOnly" active-text="只看叶子节点(filter-method)" />
<NsTree
:data="treeData"
filterable
:filter-method="leafOnly ? isLeaf : undefined"
style="width: 280px; max-width: 100%"
/>
</NsSpace>
</template>
读取和设置勾选
通过 ref 调用方法:getCheckedKeys() 读取勾选的节点,getHalfCheckedKeys() 读取半选的节点,setChecked(key, checked) 用代码勾选或取消一个节点,父子关联的规则和点复选框一样。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const treeData: TreeNodeData[] = [
{
id: 1,
label: '研发中心',
children: [
{
id: 11,
label: '前端组',
children: [
{ id: 111, label: 'Web 小组' },
{ id: 112, label: '移动端小组' }
]
},
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
]
const treeRef = ref<InstanceType<typeof NsTree>>()
const result = ref('')
const read = () => {
const checked = treeRef.value?.getCheckedKeys() ?? []
const halfChecked = treeRef.value?.getHalfCheckedKeys() ?? []
result.value = `勾选:${checked.join('、') || '无'};半选:${halfChecked.join('、') || '无'}`
}
const setChecked = (key: number, checked: boolean) => {
treeRef.value?.setChecked(key, checked)
read()
}
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<NsButton size="small" @click="setChecked(21, true)">勾选“华东大区”</NsButton>
<NsButton size="small" @click="setChecked(11, true)">勾选“前端组”</NsButton>
<NsButton size="small" @click="setChecked(11, false)">取消“前端组”</NsButton>
<NsButton size="small" type="primary" @click="read">读取勾选</NsButton>
</NsSpace>
<NsTree ref="treeRef" :data="treeData" show-checkbox default-expand-all />
<p>{{ result || '点上面的按钮试试' }}</p>
</NsSpace>
</template>
懒加载
加上 lazy 并传 load 方法后,子节点在第一次展开时才加载,data 里只放第一层节点就行。load 的参数是要展开的节点,返回一个 Promise,结果是它的子节点数组:
- 没有
children字段、也没标isLeaf: true的节点都显示展开箭头。展开时箭头换成转圈的加载图标,加载完把结果写进这个节点的children,再展开它。 - 加载过的节点再收起、展开不会重复加载。返回空数组时节点变成叶子,箭头消失。
- 已经知道没有下级的节点标上
isLeaf: true(或者直接给children: []),不显示箭头,也不会调用load。
下面用 setTimeout 模拟请求,0.8 秒后返回下级地区。“苏州市”返回空数组,“上海市”标了 isLeaf:
<script setup lang="ts">
import { ref } from 'vue'
import { NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const provinces: TreeNodeData[] = [
{ id: 'zj', label: '浙江省' },
{ id: 'js', label: '江苏省' },
{ id: 'sh', label: '上海市(isLeaf)', isLeaf: true }
]
// 模拟后端:每个地区的下级
const regions: Record<string, TreeNodeData[]> = {
zj: [
{ id: 'hz', label: '杭州市' },
{ id: 'nb', label: '宁波市' }
],
js: [
{ id: 'nj', label: '南京市' },
{ id: 'sz', label: '苏州市(没有下级)' }
],
hz: [
{ id: 'xh', label: '西湖区', isLeaf: true },
{ id: 'bj', label: '滨江区', isLeaf: true }
],
nb: [{ id: 'hs', label: '海曙区', isLeaf: true }],
nj: [
{ id: 'xw', label: '玄武区', isLeaf: true },
{ id: 'gl', label: '鼓楼区', isLeaf: true }
]
}
const logs = ref<string[]>([])
const load = (node: TreeNodeData) =>
new Promise<TreeNodeData[]>((resolve) => {
logs.value = [`加载“${node.label}”的下级…`, ...logs.value].slice(0, 6)
window.setTimeout(() => resolve(regions[String(node.id)] ?? []), 800)
})
</script>
<template>
<NsSpace wrap align="start" :size="32">
<NsTree :data="provinces" lazy :load="load" style="width: 260px" />
<div>
<p v-if="logs.length === 0" style="margin: 0">展开节点试试:第一次展开时才加载</p>
<p v-for="(text, index) in logs" :key="index" style="margin: 0 0 4px">{{ text }}</p>
</div>
</NsSpace>
</template>
加载失败和重试
load 返回的 Promise 失败(reject)或者 load 直接抛错时,触发 load-error,参数里有节点 node、它的 key 和错误 error。节点保持收起,箭头恢复原样,再展开一次会重新调用 load。下面“华南大区”第一次加载会失败,第二次成功:
<script setup lang="ts">
import { NsMessage, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const data: TreeNodeData[] = [
{ id: 'east', label: '华东大区' },
{ id: 'south', label: '华南大区(第一次会失败)' }
]
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('网络超时'))
return
}
resolve([1, 2, 3].map((i) => ({ id: `${node.id}-${i}`, label: `门店 ${i}`, isLeaf: true })))
}, 800)
})
const onLoadError = ({ node, error }: { node: TreeNodeData; error: unknown }) => {
NsMessage.error(`“${node.label}”加载失败:${(error as Error).message},再展开一次试试`)
}
</script>
<template>
<NsTree :data="data" lazy :load="load" style="max-width: 320px" @load-error="onLoadError" />
</template>
懒加载和勾选、搜索
懒加载可以和复选框、搜索框、default-expand-all 一起用:
- 父子关联照常生效:已经勾选的节点加载出子节点后,子节点也是勾选的,
v-model:checked-keys里会补上它们的 key;checked-keys里提前写了还没加载的子节点的 key 时,加载出来后父节点显示半选。 - 搜索、过滤只在已经加载出来的节点里找;搜索时展开命中的节点也会加载,加载完保持展开。
default-expand-all只展开已经有子节点的节点,不会自动加载还没加载的节点;后来加载出来的子节点里自带了下级的,也会展开。
后端返回的字段名不是 isLeaf 时,用 props 的 isLeaf 指定。下面数据里用 leaf 表示叶子、name 是节点文字;“研发中心”一开始就是勾选的,展开后加载出来的节点也都是勾选的:
<script setup lang="ts">
import { ref } from 'vue'
import { NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
const data: TreeNodeData[] = [
{ id: 'dev', name: '研发中心', leaf: false },
{ id: 'market', name: '市场部', leaf: false },
{ id: 'finance', name: '财务部', leaf: true }
]
const departments: Record<string, TreeNodeData[]> = {
dev: [
{ id: 'fe', name: '前端组', leaf: false },
{ id: 'be', name: '后端组', leaf: true }
],
fe: [
{ id: 'web', name: 'Web 小组', leaf: true },
{ id: 'app', name: '移动端小组', leaf: true }
],
market: [
{ id: 'east', name: '华东大区', leaf: true },
{ id: 'south', name: '华南大区', 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>
<NsSpace direction="vertical" align="start">
<NsTree
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">勾选的 key:{{ checkedKeys }}</p>
</NsSpace>
</template>
拖拽节点
加上 draggable 后可以用鼠标拖动节点,放到另一个节点的前面、后面或里面。鼠标在目标节点这一行的上 1/4 是放到前面,下 1/4 是放到后面,这两种都显示一条主色的线;中间是放进里面,整行高亮,放下后成为它的最后一个子节点,它会自动展开。放到一个展开的节点后面时,线画在它所有子节点的下面,也就是真正放下的位置。
放下以后树直接修改 data:把节点从原来的 children(或根数组)里拿出来,插到新的位置。data 用 ref 定义时,页面上其他用到它的地方会跟着更新,例如下面右边按 data 列出的结构:
<script setup lang="ts">
import { computed, ref } from 'vue'
import { NsMessage, NsSpace, NsTree } from '@ns/ui'
import type { TreeDropData, TreeNodeData } from '@ns/ui'
const data = ref<TreeNodeData[]>([
{
id: 1,
label: '研发中心',
children: [
{ id: 11, label: '前端组' },
{ id: 12, label: '后端组' }
]
},
{
id: 2,
label: '市场部',
children: [
{ id: 21, label: '华东大区' },
{ id: 22, label: '华南大区' }
]
},
{ id: 3, label: '财务部' }
])
// 按 data 一层层列出节点,用来看拖完以后数据变成了什么样
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: '前面', after: '后面', inner: '里面' }
const onDrop = ({ draggingNode, dropNode, dropType }: TreeDropData) => {
NsMessage.success(`“${draggingNode.label}”放到了“${dropNode.label}”${positions[dropType]}`)
}
</script>
<template>
<NsSpace wrap align="start" :size="32">
<NsTree :data="data" draggable default-expand-all style="width: 240px" @node-drop="onDrop" />
<pre style="margin: 0; line-height: 1.8">{{ structure }}</pre>
</NsSpace>
</template>
data 不是 ref(例如直接传一个普通数组)时树照样会更新,只是页面上别处读这个数组时不会跟着刷新。data 来自状态管理(store)、不想让组件直接改它时,可以传一份拷贝给树,在 node-drop 里按 draggingNode、dropNode、dropType 把同样的移动同步回去,或者提交给后端后重新拉取数据。
限制拖放
allow-drag 决定节点能不能拖,返回 false 时不能拖(禁用的节点本来就不能拖)。allow-drop 决定能不能放,参数是正在拖的节点、目标节点和放置位置 'before' | 'after' | 'inner',返回 false 时不能放到这个位置;鼠标位置对应的那一种不能放时,自动换成能放的位置(例如不能放进里面时,上半行放到前面、下半行放到后面)。
另外这几种情况始终不能放:放到自己身上或者自己的子孙节点上;放进禁用的节点里面(禁用的节点展不开,放进去就看不到了);懒加载时放进还没加载过的节点里面。
下面“项目”不能拖,文件只能放进文件夹里面,所有节点都只能留在“项目”下面:
<script setup lang="ts">
import { ref } from 'vue'
import { NsIcon, NsTree } from '@ns/ui'
import type { TreeDropType, TreeNodeData } from '@ns/ui'
const data = ref<TreeNodeData[]>([
{
id: 'project',
label: '项目',
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>
<NsTree
:data="data"
draggable
default-expand-all
:allow-drag="allowDrag"
:allow-drop="allowDrop"
style="max-width: 320px"
>
<template #default="{ node }">
<span class="file-node">
<NsIcon :name="node.type === 'folder' ? 'folder' : 'file'" />
{{ node.label }}
</span>
</template>
</NsTree>
</template>
<style scoped>
.file-node {
display: inline-flex;
align-items: center;
gap: 6px;
}
</style>
拖拽事件
拖拽过程中依次触发这些事件,参数里都有正在拖的节点 draggingNode、它的 draggingKey 和原生事件 event:
node-drag-start:开始拖时触发,参数是{ node, key, event }。node-drag-enter、node-drag-leave:鼠标进入、离开一个节点时触发,dropNode、dropKey是这个节点。node-drag-over:在节点上移动时不断触发,dropType是现在放下的话会放到的位置,不能放时为null。node-drag-end:拖拽结束时触发,放下、取消(按 Esc、放到树外面、放在不能放的位置)都会触发;没放下时dropNode、dropKey、dropType都是null。node-drop:放下、data已经改好之后触发,在node-drag-end之后。
<script setup lang="ts">
import { ref } from 'vue'
import { NsSpace, NsTree } from '@ns/ui'
import type {
TreeDragData,
TreeDragEndData,
TreeDragOverData,
TreeDropData,
TreeNodeData
} from '@ns/ui'
const data = ref<TreeNodeData[]>([
{
id: 1,
label: '研发中心',
children: [
{ id: 11, label: '前端组' },
{ id: 12, label: '后端组' }
]
},
{ id: 2, label: '市场部' },
{ id: 3, label: '财务部' }
])
const positions = { before: '前面', after: '后面', inner: '里面' }
const events = ref<string[]>([])
const record = (text: string) => {
events.value = [text, ...events.value].slice(0, 8)
}
// node-drag-over 触发得很频繁,只显示最新的一次
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] : '(不能放)'}`
}
const onEnd = ({ dropNode, dropType }: TreeDragEndData) => {
over.value = ''
record(
dropNode && dropType
? `node-drag-end:放到“${dropNode.label}”${positions[dropType]}`
: 'node-drag-end:没有放下'
)
}
const onDrop = ({ draggingNode, dropNode }: TreeDropData) =>
record(`node-drop:${draggingNode.label} → ${dropNode.label}`)
</script>
<template>
<NsSpace wrap align="start" :size="32">
<NsTree
: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">拖动一个节点试试</p>
<p v-for="(text, index) in events" :key="index" style="margin: 0 0 4px">{{ text }}</p>
</div>
</NsSpace>
</template>
虚拟滚动
节点很多(几千、上万个)时加上 virtual-scroll:把展开后看得见的节点按顺序排成一行一行,只渲染可视区里的几十行,滚动时再换。要配合两个属性:
height:树的高度,默认 300(px)。写'100%'这类百分比时,父元素要有确定的高度。item-size:每行的高度,默认 32(px),所有行一样高。用默认插槽自定义节点内容时,内容不要超出这个高度。
开启后展开收起、勾选和父子关联、搜索过滤、懒加载、键盘操作都和不开时一样:用方向键移到可视区外面的节点时,列表会先滚过去。下面用脚本生成 100 个部门、每个部门 100 个小组,一共 10100 个节点,全部展开,可以切换行高试试:
<script setup lang="ts">
import { ref } from 'vue'
import { NsSegmented, NsSpace, NsTree } from '@ns/ui'
import type { TreeNodeData } from '@ns/ui'
// 100 个部门,每个部门 100 个小组
const data: TreeNodeData[] = Array.from({ length: 100 }, (_, i) => ({
id: `d${i + 1}`,
label: `部门 ${i + 1}`,
children: Array.from({ length: 100 }, (_, j) => ({
id: `d${i + 1}-${j + 1}`,
label: `部门 ${i + 1} / 小组 ${j + 1}`
}))
}))
const itemSize = ref(32)
const sizeOptions = [
{ label: '行高 32', value: 32 },
{ label: '行高 40', value: 40 }
]
const checkedKeys = ref<(string | number)[]>([])
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSegmented v-model="itemSize" :options="sizeOptions" />
<NsTree
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">一共 10100 个节点,勾选了 {{ checkedKeys.length }} 个</p>
</NsSpace>
</template>
不开虚拟滚动时也可以用 height 限制树的高度,超出时出现滚动条,所有节点照常渲染。
虚拟滚动和拖拽可以同时开:放置位置、指示线和不开时一样,被拖的节点滚出可视区后也会保留,拖拽能正常结束。拖到列表上下边缘时会不会自动滚动由浏览器决定,不滚时可以一边拖一边用滚轮滚动。
键盘操作
整棵树只占一个 Tab 停留点:按 Tab 进入树时,焦点落在上次聚焦过的节点上(第一次进入,或那个节点已经看不到时,落在第一个能看到的、没禁用的节点上),再按 Tab 就离开这棵树。在树里用方向键移动焦点:
| 按键 | 作用 |
|---|---|
| ↓、↑ | 焦点移到下一个、上一个可见节点 |
| → | 节点收起时展开;已展开时焦点移到第一个子节点 |
| ← | 节点展开时收起;否则焦点回到父节点 |
| Enter | 相当于点击节点 |
| 空格 | 有复选框时勾选或取消勾选;没有复选框时相当于点击节点 |
开了 filterable 时,搜索框是树前面的一个 Tab 停留点;在搜索框里按 ↓ 焦点直接进入树。
懒加载的节点按 → 展开时同样会加载。开了 virtual-scroll 时按键的作用不变,焦点要移到可视区外面的节点时,列表先滚过去。
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| data | TreeNodeData[] | - | 树形数据,必填 |
| props | TreeFieldNames | {} | 自定义节点数据的字段名,比 FieldNames 多一个懒加载用的 isLeaf |
| nodeKey | string | 'id' | 节点唯一标识的字段名。props.id 也传了时以 props.id 为准 |
| defaultExpandAll | boolean | false | 是否默认展开所有节点 |
| expandOnClickNode | boolean | true | 点节点时是否展开或收起,false 时只有点箭头才展开 |
| accordion | boolean | false | 手风琴模式:同一层每次只展开一个节点 |
| highlightCurrent | boolean | false | 是否高亮当前节点 |
| currentKey | string | number | null | - | 当前节点的 key,支持 v-model:current-key。配合 highlightCurrent 才会高亮 |
| showCheckbox | boolean | false | 是否显示复选框 |
| checkStrictly | boolean | false | 勾选时父子是否不关联 |
| checkedKeys | (string | number)[] | - | 勾选的节点 key,支持 v-model:checked-keys |
| filterMethod | (node: TreeNodeData) => boolean | - | 节点过滤方法,返回 true 的节点、它的父节点和子孙节点会显示 |
| filterable | boolean | false | 是否在树上方显示搜索框 |
| filterPlaceholder | string | '输入关键字过滤' | 搜索框的占位文字,也是搜索框给读屏软件的名称 |
| filterNodeMethod | (keyword: string, node: TreeNodeData) => boolean | - | 按关键字判断节点是否命中。不传时按节点文字包含关键字判断,不分大小写;和 filterMethod 同时传时两个都要满足 |
| filterEmptyText | string | '无匹配数据' | 一个节点都没命中时显示的文字,只在 filterable 时显示 |
| lazy | boolean | false | 是否懒加载子节点:没有 children、也没标 isLeaf 的节点显示箭头,第一次展开时调用 load |
| load | TreeLoadMethod | - | 懒加载子节点的方法,参数是要展开的节点,返回子节点数组的 Promise。lazy 时必传 |
| draggable | boolean | false | 是否可以拖拽节点,放下后直接移动 data 里的节点 |
| allowDrag | (node: TreeNodeData) => boolean | - | 节点能不能拖,返回 false 时不能拖。禁用的节点始终不能拖 |
| allowDrop | (draggingNode, dropNode, type: TreeDropType) => boolean | - | 能不能放到目标节点的 type 位置(前面、后面、里面),返回 false 时不能放 |
| virtualScroll | boolean | false | 是否开启虚拟滚动,只渲染看得见的行,适合几千上万个节点 |
| height | number | string | - | 树的高度,数字按 px 处理,超出时滚动。开启 virtualScroll 时默认 300 |
| itemSize | number | 32 | 虚拟滚动时每行的高度(px) |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| node-click | (data: { node: TreeNodeData; key: string | number }) | 点击节点时触发。点箭头、点复选框、点禁用的节点不触发 |
| node-expand | (data: { node: TreeNodeData; key: string | number }) | 展开节点时触发。懒加载的节点在加载成功、展开之后才触发 |
| node-collapse | (data: { node: TreeNodeData; key: string | number }) | 收起节点时触发 |
| check | (data: { checkedKeys: (string | number)[]; node: TreeNodeData; key: string | number }) | 勾选或取消勾选节点时触发,checkedKeys 是操作之后全部勾选的 key |
| check-change | (data: { node: TreeNodeData; checked: boolean; key: string | number }) | 勾选或取消勾选节点时触发,checked 是被操作节点的新状态 |
| update:checkedKeys | (keys: (string | number)[]) | 勾选的 key 变化时触发,v-model:checked-keys 用 |
| update:currentKey | (key: string | number | null) | 当前节点变化时触发,v-model:current-key 用 |
| load-error | (data: { node: TreeNodeData; key: string | number; error: unknown }) | 懒加载失败(load 的 Promise 失败或抛错)时触发,节点保持收起 |
| node-drag-start | (data: { node: TreeNodeData; key: string | number; event: DragEvent }) | 开始拖拽节点时触发 |
| node-drag-enter | (data: TreeDragData) | 拖拽时鼠标进入一个节点时触发 |
| node-drag-leave | (data: TreeDragData) | 拖拽时鼠标离开一个节点(包括拖出整棵树)时触发 |
| node-drag-over | (data: TreeDragOverData) | 拖拽时在节点上移动时不断触发,dropType 为 null 表示不能放 |
| node-drag-end | (data: TreeDragEndData) | 拖拽结束时触发,放下、取消都触发;没放下时 dropNode 等为 null |
| node-drop | (data: TreeDropData) | 放下、data 已经改好之后触发,在 node-drag-end 之后 |
Slots
| 插槽 | 作用域参数 | 说明 |
|---|---|---|
| default | { node: TreeNodeData, level: number } | 自定义节点内容,不写时显示节点的文字字段 |
方法
通过组件的 ref 调用。
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| getCheckedKeys | - | (string | number)[] | 返回当前勾选的节点 key |
| getHalfCheckedKeys | - | (string | number)[] | 返回当前半选的节点 key |
| setChecked | (key: string | number, checked: boolean) | void | 勾选或取消勾选一个节点,父子关联的规则和点复选框一样;禁用的节点也可以设置 |
| filter | (keyword?: string) | void | 按关键字过滤节点,和在搜索框里输入一样(有搜索框时搜索框也显示这个关键字);传空字符串或不传时取消。不开 filterable 也能用 |
类型
import type {
TreeNodeData,
FieldNames,
TreeFieldNames,
TreeLoadMethod,
TreeDropType,
TreeDragData,
TreeDragOverData,
TreeDropData,
TreeDragEndData
} from '@ns/ui'
interface TreeNodeData {
id?: string | number
label?: string
children?: TreeNodeData[]
disabled?: boolean
/** 懒加载时标记为叶子节点:不显示展开箭头,也不会调用 load */
isLeaf?: boolean
/** 可以带任意其他字段,自定义节点内容时能用到 */
[key: string]: unknown
}
/** 数据里对应的字段名(TreeSelect 的 props 也用它) */
interface FieldNames {
label?: string
children?: string
disabled?: string
id?: string
}
/** Tree 的 props 属性:多一个懒加载时标记叶子节点的字段,默认 isLeaf */
interface TreeFieldNames extends FieldNames {
isLeaf?: string
}
/** 懒加载子节点的方法:Promise 失败时节点保持收起,再次展开重新调用 */
type TreeLoadMethod = (node: TreeNodeData) => Promise<TreeNodeData[]>
/** 放置位置:目标节点前面、后面,或者成为它的最后一个子节点 */
type TreeDropType = 'before' | 'after' | 'inner'
/** node-drag-enter、node-drag-leave 的参数 */
interface TreeDragData {
/** 正在拖的节点 */
draggingNode: TreeNodeData
draggingKey: string | number
/** 鼠标下面的节点 */
dropNode: TreeNodeData
dropKey: string | number
event: DragEvent
}
/** node-drag-over 的参数:不能放时 dropType 为 null */
interface TreeDragOverData extends TreeDragData {
dropType: TreeDropType | null
}
/** node-drop 的参数 */
interface TreeDropData extends TreeDragData {
dropType: TreeDropType
}
/** node-drag-end 的参数:没放下时 dropNode、dropKey、dropType 为 null */
interface TreeDragEndData {
draggingNode: TreeNodeData
draggingKey: string | number
dropNode: TreeNodeData | null
dropKey: string | number | null
dropType: TreeDropType | null
event: DragEvent
}
注意事项
- 每个节点的 key 在整棵树里必须唯一。节点没有 key 时控制台会有警告,展开和勾选都会出错。
- 父子关联时,如果父节点下面有禁用且没勾选的子节点,父节点最多只能到半选;这时再点一次父节点的复选框是取消它下面已勾选的节点。
- 父节点本身被禁用时,即使子节点全部勾选,它也不会自动变成勾选。
- 禁用的节点不能展开也不能收起。配合
default-expand-all时它是展开的,而且收不起来;没有默认展开时它下面的节点看不到。 setChecked调用后会触发update:checkedKeys、check和check-change,和用户点复选框一样。- Tree 没有
size,节点的复选框固定是 default 尺寸(16px 方框),放在NsForm、NsConfigProvider里也不跟着它们的size变。在NsTreeSelect的面板里时跟着 TreeSelect 的尺寸。 - 外部传了
currentKey(包括用v-model:current-key)时,当前节点完全由这个值决定;只监听update:currentKey而不更新它,高亮不会变。 data为空时什么都不显示,需要空状态提示时自己在外面判断。- 懒加载、拖拽会直接修改传入的
data:加载出的子节点写进节点的children,拖拽时把节点从原来的数组里移到新位置。data用ref定义时页面上其他地方会跟着更新;data是只读的(例如readonly()、状态库的 getter)时改不了,要传一份可以修改的拷贝。 - 懒加载以节点有没有
children数组判断加载过没有。想重新加载某个节点时,把它的children删掉(设成undefined)再收起、展开。 - 懒加载只加载子节点,根节点由
data传入。load加载过程中再点这个节点不会重复加载。 - 拖拽用的是浏览器原生的拖放(HTML5 Drag and Drop),只能用鼠标操作:手机、平板的触摸屏上不能拖,也没有对应的键盘操作。不能拖到别的树或者页面上的其他元素里。
- 父子关联时,拖拽后会按子节点重新计算原来的父节点和新的父节点的勾选状态,变了时触发
update:checkedKeys(不触发check、check-change)。父节点的子节点全部被拖走后,它保持原来的勾选状态。 - 虚拟滚动时每一行一样高(
item-size),节点按行平铺渲染,没有.ns-tree-node__children这一层,子节点的缩进写在行上;读屏软件靠aria-level、aria-setsize、aria-posinset知道层级。 - 虚拟滚动和拖拽可以同时开,被拖的节点滚出可视区也会保留,拖拽能正常结束。拖到列表上下边缘时会不会自动滚动由浏览器决定。
- 开了
filterable时组件外面多一层.ns-tree-wrapper,传给组件的class、style落在这一层上;.ns-tree仍然是节点列表(role="tree")。 - 搜索框固定是 default 尺寸(32px 高),和节点行一样高,不跟着
NsForm、NsConfigProvider的size变。放在表单项里时,搜索框不算表单项的控件:不关联标签、输入时不触发校验,表单禁用时也能搜索。 - 搜索时展开的节点、搜索过程中手动展开或收起的节点,清空关键字后都会回到开始搜索之前的状态。搜索过程中每输入一个字,展开状态会按新的结果重新计算。
- 高亮只用在默认显示的节点文字上,用了默认插槽自定义节点内容时不高亮。
- 再点一次当前节点,高亮不会取消,也不会再触发
update:currentKey(node-click照常触发)。默认expandOnClickNode为true,再点有子节点的节点会收起它;不想这样时设:expand-on-click-node="false"。 - 每输入一个字都会重新过滤整棵树,没有防抖。节点有上万个时,可以不开
filterable,自己的输入框防抖后调用filter()。
优化点
- [x] 支持节点过滤(
filterMethod) - [x] 内置搜索框(
filterable),命中的文字高亮 - [x] 支持懒加载子节点(
lazy、load) - [x] 支持节点拖拽(
draggable) - [ ] 支持节点右键菜单
- [x] 支持虚拟滚动优化大数据渲染(
virtualScroll) - [ ] 支持默认展开指定的节点、用代码展开或收起节点(目前只有
defaultExpandAll) - [ ] 数据为空时显示空状态
- [ ] 禁用的节点允许展开和收起,只禁止点击和勾选