高级布局
本页汇总源码 demo 中四类高级布局配置。建议先确保基础静态或动态示例可运行,再逐项启用。
动态节点尺寸
根据业务内容决定节点尺寸:
ts
function calcNodeSize(item: Record<string, unknown>) {
const hasDescription = Boolean(item.description)
const fieldCount = Object.keys(item).length
return {
width: hasDescription ? 300 : 220,
height: 72 + Math.max(0, fieldCount - 4) * 20,
}
}
layout: {
spaceX: 24,
spaceY: 40,
nodeSize: calcNodeSize,
}卡片必须使用布局结果中的尺寸:
vue
<div :style="{ width: `${node.width}px`, height: `${node.height}px` }">
<!-- 根据 node.info 渲染不同内容 -->
</div>间距与方向
ts
const sdk = new OrgTreeCore({
el: '#tree',
direction: 'down',
layout: {
spaceX: 48,
spaceY: 72,
},
data,
})切换方向:
ts
sdk.setDirection('right')
await sdk.loadData()当前没有运行时修改间距的方法。间距变化时创建新 SDK 最安全。
自定义字段映射
ts
const data = [
{ nodeId: 'root', pid: null, label: '总部', city: '上海' },
{ nodeId: 'tech', pid: 'root', label: '技术中心', city: '北京' },
]
layout: {
spaceX: 40,
spaceY: 56,
fieldMap: {
id: 'nodeId',
parentId: 'pid',
},
}渲染时业务数据保持原样:node.info.label、node.info.city。
子节点排序
ts
layout: {
spaceX: 40,
spaceY: 56,
transformChildren: (_parent, children) =>
[...children].sort(
(a, b) => Number(a.order) - Number(b.order),
),
}转换函数会递归应用到每一个父节点,而不是只处理根节点的孩子。
也可以根据父节点采用不同规则:
ts
transformChildren: (parent, children) => {
if (parent.type === 'department')
return [...children].sort(byHeadcount)
return children
}权重分层
同一个父节点的直接子节点可以通过 weight 分布在不同深度:
ts
const data = [
{ id: 'root', parentId: null, name: 'CEO', level: 'C-Level', weight: 0 },
{ id: 'vp', parentId: 'root', name: '技术 VP', level: 'VP', weight: 1 },
{ id: 'director', parentId: 'root', name: '技术总监', level: 'Director', weight: 2 },
]
layout: {
spaceX: 40,
spaceY: 60,
fieldMap: {
id: 'id',
parentId: 'parentId',
weight: 'weight',
},
}权重分层只在 down 方向生效。切到 right 后,节点按普通父子深度排列。
组合配置
这些能力可以组合:
ts
layout: {
spaceX: 40,
spaceY: 64,
nodeSize: calcNodeSize,
fieldMap: {
id: 'nodeId',
parentId: 'pid',
weight: 'levelWeight',
},
transformChildren: sortByOrder,
isLeaf: node => node.childCount === 0,
}排查问题时按以下顺序逐项启用:字段映射 → 数据加载 → 固定尺寸 → 动态尺寸 → 排序 → 权重。