Standalone 接入
@org-tree/standalone 把 Core、Vue、运行时依赖和样式打包为 IIFE/UMD 文件,适合无法接入 npm 构建链的页面。
获取构建产物
在仓库中构建:
bash
pnpm build:standalone产物位于 packages/standalone/dist/:
text
dist/
├─ org-tree.iife.js
├─ org-tree.umd.js
└─ org-tree.css将 IIFE 文件和 CSS 复制到静态资源服务器即可。浏览器全局变量名是 OrgTree。
最小 HTML
html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>组织架构树</title>
<link rel="stylesheet" href="./org-tree.css">
<style>
html,
body,
#tree {
width: 100%;
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="tree"></div>
<script src="./org-tree.iife.js"></script>
<script>
const tree = OrgTree.createOrgTree('#tree', {
direction: 'down',
layout: {
spaceX: 32,
spaceY: 56,
nodeSize: { width: 200, height: 80 },
},
data: [
{ id: 'root', parentId: null, name: '集团总部' },
{ id: 'tech', parentId: 'root', name: '技术中心' },
{ id: 'product', parentId: 'root', name: '产品中心' },
],
})
</script>
</body>
</html>createOrgTree() 会创建渲染实例并自动调用 loadData(),无需再次手动初始化。
自定义节点
原生 HTML 场景下,renderNode 返回一个 HTMLElement:
html
<script>
const tree = OrgTree.createOrgTree('#tree', {
layout: {
spaceX: 32,
spaceY: 56,
nodeSize: { width: 220, height: 88 },
},
data,
renderNode({ node, isLeaf, expanded, loading }) {
const card = document.createElement('article')
card.className = 'business-node'
card.style.width = `${node.width}px`
card.style.height = `${node.height}px`
const name = document.createElement('strong')
name.textContent = String(node.info.name ?? node.nodeId)
card.appendChild(name)
if (loading) {
const state = document.createElement('small')
state.textContent = '正在加载…'
card.appendChild(state)
}
return card
},
})
</script>css
.business-node {
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #fff;
border: 1px solid #e5e7eb;
border-radius: 10px;
box-shadow: 0 6px 18px rgb(24 32 56 / 8%);
}回调上下文与 Vue 插槽一致:node、isLeaf、expanded、loading。
不要使用 innerHTML 拼接接口数据
示例通过 textContent 写入业务内容,避免接口字段被解释为不受信任的 HTML。
动态数据
html
<script>
const tree = OrgTree.createOrgTree('#tree', {
layout: {
spaceX: 32,
spaceY: 56,
isLeaf: node => node.isLeaf === true,
},
api: {
async init() {
const response = await fetch('/api/org-tree')
return response.json()
},
async loadChildren(nodeId) {
const response = await fetch(`/api/org-tree/${nodeId}/children`)
return response.json()
},
},
})
</script>data 和 api 必须二选一。
访问底层 SDK
createOrgTree() 返回的实例包含 sdk:
js
await tree.sdk.expand({ nodeId: 'tech' })
tree.sdk.collapse({ nodeId: 'tech' })
tree.sdk.setDirection('right')
await tree.sdk.loadData()
tree.sdk.setNodeStatus('tech', { highlight: true })Standalone 使用与 Core 完全相同的状态和事件方法。
销毁实例
页面卸载、路由切换或容器复用前调用 destroy():
js
tree.destroy()它会卸载内部 Vue 应用并清空容器。
何时不要使用 Standalone
Vue 3 工程应优先安装 Core 与 Vue 包,这样可以获得源码类型、按需编译和更自然的组件插槽。Standalone 更适合静态页面、微前端外嵌页和构建工具不可控的系统。