引入 mxGraph
旧方法
yarn add mxgraph-js # 这个包里的 mxgraph 版本号为 3.6.0
import { mxGraph, mxUtils, mxHierarchicalLayout, mxCellOverlay, mxEvent, mxRubberband, mxKeyHandler, mxConstants, mxImage, } from 'mxgraph-js';
官方用法
yarn add mxgraph # mxgraph 版本号 4.2.2
import * as mxgraph from 'mxgraph'; const { mxGraph, mxUtils, mxHierarchicalLayout, mxCellOverlay, mxEvent, mxRubberband, mxKeyHandler, mxConstants, mxImage, } = mxgraph();
mxgraph 导出的不是库本身,而是它的工厂方法。所以可以这样使用:
// ./mxgraph.js import mxgraphFactory from 'mxgraph' export default mxgraphFactory({ // here should be your paths to mxgraph's assets (it's optional) mxImageBasePath: 'assets/mxgraph/images', mxBasePath: 'assets/mxgraph' }) // ./app.js import mxgraph from './mxgraph' new mxgraph.mxGraph()
新方法
yarn add mxgraph4vue;
<div ref="graph_container" class="graph-container"></div> <style lang="scss" scoped> .graph-container { position: relative; height: 400px; } </style>
import * as mxgraph from 'mxgraph4vue'; import 'mxgraph4vue/javascript/src/css/common.css'; const { mxGraph, mxUtils, mxHierarchicalLayout, mxCellOverlay, mxEvent, mxRubberband, mxKeyHandler, mxConstants, mxImage, } = mxgraph(); import icon from './images/icon.png'; export default { mounted() { let graph = new mxGraph(this.$refs.graph_container); graph.view.rendering = false; // 先不渲染,最后要调整宽高尺寸 // 启用拖动平移 graph.setPanning(true); graph.panningHandler.useLeftButtonForPanning = true; // 自定义 tooltip graph.setTooltips(true); graph.getTooltipForCell = function (cell) { var data = cell.data || {}; var tip = []; for (const key in data) { if (Object.hasOwnProperty.call(data, key)) { const value = data[key]; tip.push(`${key}: ${value}`); } } return tip.length ? tip.join('\n') : cell.value; }; // 右键菜单 mxEvent.disableContextMenu(this.$refs.graph_container); graph.popupMenuHandler.factoryMethod = function (menu, cell, evt) { return function (graph, menu, cell, evt) { if (cell != null) { menu.addItem('MenuItem1', icon, function () { mxUtils.alert('MenuItem1'); }); } }; }; let root = graph.getDefaultParent(); graph.getModel().beginUpdate(); try { let v1 = graph.insertVertex(root, null, 'Hello,', 0, 0, 80, 30); let v2 = graph.insertVertex(root, null, 'World!', 0, 0, 80, 30); let e1 = graph.insertEdge(root, null, '', v1, v2); v1.data = {key: 'value', key1: 'v1'}; // 自定义数据 // 自动布局 this.layout = new mxHierarchicalLayout(graph, mxConstants.DIRECTION_NORTH); this.layout.execute(root); } finally { graph.getModel().endUpdate(); graph.fit(); // 让图填充整个容器 graph.view.rendering = true; graph.refresh(); graph.zoomOut(); // 缩小一些给周围留个边距 } }, }