RelationGraphInstance 公开接口
RelationGraphInstance 是 relation-graph 的核心实例对象。
它负责数据读写、视图控制、布局执行、交互控制、导入导出等能力。
1. 如何获取实例
A. 通过 onReady(推荐)
let graphInstance: RelationGraphInstance | undefined;
const onReady = (instance: RelationGraphInstance) => {
graphInstance = instance;
};
B. 通过组件引用(不同框架写法略有差异)
const graphInstance = graphRef.value?.getInstance?.();
2. API 分组总览
RelationGraphInstance 公开 API 可以按职责划分为:
- 基础能力:
generateNewUUID、enableDebugLog、addEventHandler - 坐标与视图:
getViewXyByEvent、getCanvasXyByViewXy、getViewXyByCanvasXy - 数据查询:
getNodeById、getLineById、getNodes、getLines、getLinks - 图关系分析:
getNodeRelatedNodes、getNetworkNodesByNode、getNodesRectBox - CRUD:
addNodes、addLines、updateNode、updateLine、removeNodeById - 交互控制:
setCheckedNode、clearChecked、expandNode、collapseNode - 缩放与画布:
zoom、setZoom、zoomToFit、moveToCenter - 布局控制:
doLayout、createLayout、startAutoLayout、stopAutoLayout - 编辑态控制:
setEditingNodes、setEditingLine、startMoveLineVertex - 数据导入导出:
setJsonData、appendJsonData、getGraphJsonData、clearGraph - 图片生成:
prepareForImageGeneration、restoreAfterImageGeneration
3. 高价值方法速查
| 场景 | 常用方法 |
|---|---|
| 初始化图数据 | setJsonData(jsonData) |
| 追加图数据 | appendJsonData(jsonData, isRelayout?) |
| 获取完整图数据 | getGraphJsonData() |
| 批量加点加线 | addNodes(nodes)、addLines(lines) |
| 更新样式/业务数据 | updateNode(nodeId, patch)、updateLine(lineId, patch) |
| 查找实体 | getNodeById、getLineById、getLinkByLineId |
| 聚焦视图 | moveToCenter(nodes?)、zoomToFit(nodes?) |
| 手动布局 | doLayout(customRootNode?)、createLayout(options) |
| 全屏 | fullscreen(newValue?) |
| 导出图片前后处理 | prepareForImageGeneration()、restoreAfterImageGeneration() |
4. 常见调用流程
A. 首次加载并自适应
await graphInstance.setJsonData(jsonData);
graphInstance.moveToCenter();
graphInstance.zoomToFit();
B. 动态加节点和连线
const nodeId = graphInstance.generateNewNodeId(8);
graphInstance.addNodes([{ id: nodeId, text: "New Node" }]);
graphInstance.addLines([{ from: "a", to: nodeId, text: "new link" }]);
graphInstance.moveToCenter();
C. 更新节点与连线数据
graphInstance.updateNode("node-1", { color: "#0ea5e9", borderWidth: 2 });
graphInstance.updateNodeData("node-1", { owner: "team-a", score: 98 });
graphInstance.updateLine("line-1", { color: "#ef4444", lineWidth: 2 });
graphInstance.updateLineData("line-1", { status: "warning" });
5. 与事件系统联动的关键点
- 连线创建校验:在
beforeCreateLine中返回false可阻止连线创建。 - 连线端点修改场景:在
onLineBeCreated中通常要addLines(...)让新线生效。 - 缩放/滚动拦截:
beforeZoomStart、beforeScrollStart可作为权限或模式控制入口。
6. 视图坐标转换(高频)
复杂交互(右键菜单、拖拽创建、画布落点)常用以下方法:
getViewXyByEvent(e):事件坐标 -> 视口坐标getCanvasXyByViewXy({ x, y }):视口坐标 -> 画布坐标getViewXyByCanvasXy({ x, y }):画布坐标 -> 视口坐标
7. 布局相关接口建议
- 静态图:
doLayout()一次性布局即可。 - 力导向动态图:配合
startAutoLayout()/stopAutoLayout()控制计算时机。 - 定制布局:
createLayout(layoutOptions, isMainLayout?)对指定节点集执行布局。
8. 导入导出与调试
- 导出数据:
getGraphJsonData()、printGraphJsonData() - 调试开关:
enableDebugLog(true/false) - 清图重建:
clearGraph()+setJsonData(...)
9. 实践建议
- 在应用层维护唯一的
graphInstance引用,避免多处重复获取。 - 优先走实例 API 改图,不要直接改内部运行时对象。
- 对频繁操作(拖拽、缩放回调)避免重计算,必要时节流。
- 将业务规则放在事件层,实例 API 专注“执行动作”。