本文简单记录一下在项目中引入 mxGraph 到 React 和 Vue中。关于 mxGraph 是什么请自行搜索。

下面是 mxGraph 所涉及的仓库地址

在 React 中引入

这里基干 ES6 的写法引入示例:

import React, { useCallback } from 'react'
import 'mxgraph/javascript/src/css/common.css'
import 'style.css'

const mx = require('mxgraph')({
  mxBasePath: 'mxgraph'
})
const { mxGraph } = mx

function App() {
  let graph = null
  
  const containerRef = useCallback(node => {
    if (node != null) {
      initGraph(node)
      const parent = graph.getDefaultParent()
      graph.getModel().beginUpdate()
      try {
        const v1 = graph.insertVertex(parent, null, 'vertex 1', 0, 0, 80, 20)
        const v2 = graph.insertVertex(parent, null, 'vertex 2', 100, 0, 80, 20)
        graph.insertEdge(parent, null, '', v1, v2)
      } finally {
        graph.getModel().endUpdate();
      }
    }
  }, [])
  
  function initGraph(container) {
    graph = new mxGraph(container)
  }
  
  return (
      <div className="app">
      <div ref={containerRef} className="container"></div>
    </div>
  )
}

export default App

在 Vue 中引入

这是基于 Vue + Typescript 方式的引入示例:

import { Component, Vue, Ref } from 'vue-property-decorator'
import { mxgraph } from 'mxgraph'
require('mxgraph/javascript/src/css/common.css')
import style from './style.scss'

const mx: typeof mxgraph = require('mxgraph')({
  mxBasePath: 'mxgraph'
});

@Component
export default class Workflow extends Vue {
  private graph!: mxgraph.mxGraph;
  private v1!: mxgraph.mxCell;
  private v2!: mxgraph.mxCell;
  private edge!: mxgraph.mxCell;

  @Ref('containerRef') readonly graphContainer!: HTMLDivElement;

  public mounted() {
    this.init();
  }

  private init() {
    this.graph = new mx.mxGraph(this.graphContainer);
    mx.mxEvent.disableContextMenu(this.graphContainer);
    const parent = this.graph.getDefaultParent();

    this.graph.getModel().beginUpdate();
    try {
      this.v1 = this.graph.insertVertex(parent, null, '节点1', 20, 20, 80, 30);
      this.v2 = this.graph.insertVertex(parent, null, '节点2', 20, 120, 80, 30);
      this.edge = this.graph.insertEdge(parent, null, '', this.v1, this.v2)
    } finally {
      this.graph.getModel().endUpdate();
    }
  }

  render() {
    return (
      <div class={style.container} ref="containerRef"></div>
    )
  }
}

jenemy
1.7k 声望744 粉丝

从事前端多年,技术依然很渣的IT程序员。