安装jsplumb:

npm i jsplumb

注意jsplumb要小写 , 用 npm install jsPlumb --save 这种命令会报这样的错的: ‘jsPlumb@latest’ is not in the npm registry.

引入

(1) 可以在main.js中将jsplumb挂在vue下便于页面获取

import jsPlumb from 'jsplumb'

Vue.prototype.$jsPlumb = jsPlumb.jsPlumb

(2) 在要使用的页面引入:

import jsPlumb from 'jsplumb'

使用

参考: jsplumb中文教程

初始化

jsplumb 要放在 mounted 中, 因为它要依靠dom元素

  mounted() {
    this.jsPlumbInit();
  },
  methods: {
    jsPlumbInit() {
     
        var plumbIns = jsPlumb.jsPlumb.getInstance();
        this.plumbIns = plumbIns;
        console.log("jsPlumb实例化");
        console.log(this.plumbIns);
      
    },
  }

可以设置公共样式:

      // jsplumb 公共样式
      var common = {
        endpoint: "Blank", 
        anchor: ["Top", "Bottom", [0.5, 0, 0, -1], [0.5, 1, 0, 1]], // 锚点位置
        connector: [
          "Flowchart",
          { stub: [15, 25], cornerRadius: 5, alwaysRespectStubs: true },
        ],
        maxConnections: -1,  // 允许一个节点有无限条连线
        EndpointStyle: { radius: 4, fill: "#acd" }, //端点样式
      };

连线

 			 // label 连线
            this.plumbIns.ready(() => {
              this.plumbIns.connect(
                {
                  source: sourceNode,
                  target: targetNode,
                  paintStyle: { stroke: "Pink", strokeWidth: 1, radius: 7 },
                  overlays: [
                    ["Arrow", { width: 8, length: 8, location: 1 }],
                    [
                      "Label",
                      {
                        location: 0.9,
                        label: rela,
                        cssClass: "endpointTargetLabel1",
                        visible: true,
                        id: "label",
                      },
                    ],
                  ],
                },
                common
              );
            });

删除所有连线

ps: 不能用getAllConnections 否则删除的时候会少

      // 删除原来的所有连线
      const connections = this.plumbIns.getConnections() // 不能用getAllConnections 否则删除的时候会少
        console.log(connections)
        for (let i = 0; i < connections.length; i++) {
        this.plumbIns.deleteConnection(connections[i]);
     }

有时候绘制的时候会报错: 找不到source或者target, 是因为之前高亮的时候div没有渲染完成:

      // 等待渲染完成, 绘制连线
      setTimeout(() => {
        this.drawLabel();
      }, 500);

重新编辑后连线不能立即显示

在调用连线函数之前重新初始化一下 jsplumb 的实例 就可以了

效果:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐