在 HTML / Web Components 中使用
本页说明如何在纯 HTML 或非前端框架环境中,通过 Web Components 使用 relation-graph。
1. 引入方式
可以使用 CDN 或 ESM 方式。
CDN(最快)
<script src="https://unpkg.com/relation-graph-webcomponents@latest/lib/relation-graph-webcomponents.min.js"></script>
浏览器 ESM
<script type="module">
import * as rg from 'https://unpkg.com/relation-graph-webcomponents@latest/lib/relation-graph-webcomponents.mjs';
</script>
2. 与框架版本的关键差异
- 没有
RGProvider/RGHooks。 - 通过
onReady事件拿到graphInstance。 - 通过
graphInstanceAPI 直接管理图谱数据和状态。
3. 最小 HTML 示例
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>RelationGraph Web Components</title>
</head>
<body>
<div style="width: 100vw; height: 100vh; background-color: #ffffff;">
<relation-graph id="my-graph"></relation-graph>
</div>
<script type="module">
import * as rg from 'https://unpkg.com/relation-graph-webcomponents@latest/lib/relation-graph-webcomponents.mjs';
const rgElement = document.getElementById('my-graph');
let graphInstance;
const graphOptions = {
showToolBar: false,
wheelEventAction: 'scroll',
dragEventAction: 'move'
};
const jsonData = {
rootId: 'node-a',
nodes: [
{ id: 'node-a', text: 'Alpha' },
{ id: 'node-b', text: 'Beta' },
{ id: 'node-c', text: 'Gamma' }
],
lines: [
{ from: 'node-a', to: 'node-b', text: 'A -> B' },
{ from: 'node-b', to: 'node-c', text: 'B -> C' }
]
};
const initializeGraph = () => {
graphInstance.setJsonData(jsonData);
graphInstance.moveToCenter();
graphInstance.zoomToFit();
};
rgElement.addEventListener('onReady', (event) => {
graphInstance = event.detail[0];
graphInstance.updateOptions(graphOptions);
initializeGraph();
});
rgElement.addEventListener('onNodeClick', (event) => {
const [node] = event.detail;
console.log('node click:', node && node.id);
});
rgElement.addEventListener('onLineClick', (event) => {
const [line] = event.detail;
console.log('line click:', line && line.from, line && line.to);
});
</script>
</body>
</html>
4. 数据接入方式
- 一次性:
setJsonData(...) - 增量式:
addNodes(...)、addLines(...)、update/remove 系列 API - 运行时配置:
graphInstance.updateOptions(...)
5. 插槽与内置子组件
在 Web Components 模式下,可直接在 HTML 中使用插槽和内置元素,例如:
slot="view"、slot="canvas"<rg-mini-view><rg-editing-node-controller><rg-editing-reference-line><rg-editing-connect-controller><rg-connect-target>
这些元素可以帮助你在纯 HTML 环境实现编辑器能力。
6. 实践建议
<relation-graph>的显示大小由父容器决定。- 必须等待
onReady触发后再调用实例 API。 - Web Components 适合 Angular、jQuery、原生 JS 等环境。