异步懒加载
组织规模较大或权限范围按节点计算时,可以只加载首屏节点,在用户展开时再请求直接子节点。
模拟后端数据
ts
const allNodes = [
{ id: 'root', parentId: null, name: '集团总部', isLeaf: false },
{ id: 'tech', parentId: 'root', name: '技术中心', isLeaf: false },
{ id: 'hr', parentId: 'root', name: '人力资源', isLeaf: true },
{ id: 'frontend', parentId: 'tech', name: '前端团队', isLeaf: true },
{ id: 'backend', parentId: 'tech', name: '后端团队', isLeaf: true },
]实现 API
ts
import type { OrgTreeApi } from '@org-tree/core'
function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}
const api: OrgTreeApi = {
async init() {
await delay(400)
return allNodes.filter(
node => node.parentId === null || node.parentId === 'root',
)
},
async loadChildren(nodeId) {
await delay(500)
return allNodes.filter(node => node.parentId === nodeId)
},
}创建 SDK
ts
const sdk = new OrgTreeCore({
el: '#tree',
direction: 'down',
layout: {
spaceX: 40,
spaceY: 56,
isLeaf: node => node.isLeaf === true,
},
api,
})
await sdk.loadData()展示加载状态
内置展开按钮在请求过程中显示加载图标。业务卡片也可以读取插槽的 loading:
vue
<OrgTree v-slot="{ node, loading, expanded, isLeaf }">
<article
class="node-card"
:class="{ 'node-card--loading': loading }"
:style="{ width: `${node.width}px`, height: `${node.height}px` }"
>
<strong>{{ node.info.name }}</strong>
<small v-if="loading">正在加载下级组织…</small>
<small v-else-if="!isLeaf">
{{ expanded ? '已展开' : '点击 + 展开' }}
</small>
</article>
</OrgTree>接入真实接口
生产 API 应保证:
init()至少返回一个根节点。loadChildren(id)只返回parentId === id的直接子节点。- 每批数据中的 ID 稳定且全局唯一。
- 所有接口都返回
isLeaf或childCount。 - 请求层统一处理鉴权、超时、错误码和数据结构校验。
完整时序和缓存建议见数据加载。