vue中使用AntV G6编写树形结构图并实现节点增删改

效果图:

  • 先在vue项目中安装antv G6
 npm install --save @antv/g6
  • 安装完之后引入,我是将整个结构图的某些相关配置进行了封装,写在了公共js文件里面,若是你们不想封装可以直接在你们相关的vue文件里面引入  
import G6 from '@antv/g6';

 

  • 然后封装名称为renderMap的函数,名字可以自定义
export function renderMap(data,graph){
  const COLLAPSE_ICON = function COLLAPSE_ICON(x, y, r) {
    return [
      ['M', x - r, y - r],
      ['a', r, r, 0, 1, 0, r * 2, 0],
      ['a', r, r, 0, 1, 0, -r * 2, 0],
      ['M', x + 2 - r, y - r],
      ['L', x + r - 2, y - r],
    ];
  };
  const EXPAND_ICON = function EXPAND_ICON(x, y, r) {
    return [
      ['M', x - r, y - r],
      ['a', r, r, 0, 1, 0, r * 2, 0],
      ['a', r, r, 0, 1, 0, -r * 2, 0],
      ['M', x + 2 - r, y - r],
      ['L', x + r - 2, y - r],
      ['M', x, y - 2 * r + 2],
      ['L', x, y - 2],
    ];
  };
  G6.Util.traverseTree(data, (d) => {
    d.leftIcon = {
      style: {
        fill: '#3759B0',
        stroke: '#e6fffb',
      },
    };
    return true;
  });
  
  G6.registerNode('icon-node', {
    options: {
      size: [60, 20],
      stroke: '#73D13D',
      fill: '#fff'
    },
    draw(cfg, group) {
      const styles = this.getShapeStyle(cfg)
      const { labelCfg = {} } = cfg
  
      const keyShape = group.addShape('rect', {
        attrs: {
          ...styles,
          x: 0,
          y: 0
        }
      })
  
      /**
       * leftIcon 格式如下:
       *  {
       *    style: ShapeStyle;
       *    img: ''
       *  }
       */
     // console.log('cfg.leftIcon', cfg.leftIcon);
      if (cfg.leftIcon) {
        const { style, img } = cfg.leftIcon
        group.addShape('rect', {
          attrs: {
            x: 10,
            y: 8,
            width: 24,
            radius: 12,
            height: styles.height - 16,
            fill: '#8c8c8c',
            ...style
          }
        })
        group.addShape('text', {
            attrs: {
              text: cfg.name,
              x: 22,
              y: 21,
              fill: '#ffffff',
              fontSize: 12,
              textAlign: 'center',
              textBaseline: 'middle',
              fontWeight: 'bold',
            },
            name: 'text-shape',
          });
        group.addShape('image', {
          attrs: {
            x: 8,
            y: 8,
            width: 24,
            height: 24,
          },
          name: 'image-shape',
        });
      }
  
      // 如果不需要动态增加或删除元素,则不需要 add 这两个 marker
      group.addShape('marker', {
        attrs: {
          x: 130,
          y: 18,
          r: 6,
          stroke: '#707070',
          cursor: 'pointer',
          symbol: EXPAND_ICON
        },
        name: 'add-item'
      })
  
      group.addShape('marker', {
        attrs: {
          x: 130,
          y: 36,
          r: 6,
          stroke: '#5C5C5C',
          cursor: 'pointer',
          symbol: COLLAPSE_ICON
        },
        name: 'remove-item'
      })
  
      if (cfg.label) {
        group.addShape('text', {
          attrs: {
            ...labelCfg.style,
            text: cfg.label,
            x: 50,
            y: 25,
          }
        })
      }
  
      return keyShape
    }
  }, 'rect')
  
  G6.registerEdge('flow-line', {
    draw(cfg, group) {
      const startPoint = cfg.startPoint;
      const endPoint = cfg.endPoint;
  
      const { style } = cfg
      const shape = group.addShape('path', {
        attrs: {
          stroke: style.stroke,
          endArrow: style.endArrow,
          path: [
            ['M', startPoint.x, startPoint.y],
            ['L', startPoint.x, (startPoint.y + endPoint.y) / 2],
            ['L', endPoint.x, (startPoint.y + endPoint.y) / 2,],
            ['L', endPoint.x, endPoint.y],
          ],
        },
      });
  
      return shape;
    }
  });
  
  const width = document.getElementById('container').scrollWidth;
  const height = document.getElementById('container').scrollHeight || 500;

  graph.data(data);
  graph.render();
  graph.fitView();

  graph.on('node:mouseenter', evt => {
    const { item } = evt
    graph.setItemState(item, 'hover', true)
  })
  
  graph.on('node:mouseleave', evt => {
    const { item } = evt
    graph.setItemState(item, 'hover', false)
  })
}
  • 然后需要在相关的vue文件中引入这个封装好的公共函数renderMap
import G6 from "@antv/g6";
import { renderMap } from "../../../assets/common/http";

  • 直接呈上完整vue文件,里面有几个需要注意的点,用注释标注了
<template>
  <div>
    <div id="container"></div>
  </div>
</template>

<script>
import G6 from "@antv/g6";  //注意引入 
import { renderMap } from "../../../assets/common/http"; //朱茵引入封装的函数
export default {
  data() {
    return {
      graph: {}, //定义一个graph对象
      data: {    //定义一个公共数据数组
        id: "root",
        label: "root",
        name: 1,
        children: [
          {
            id: "c1",
            label: "c1",
            name: 2,

            children: [
              {
                id: "c1-1",
                label: "c1-1",
                name: 3
              },
              {
                id: "c1-2",
                label: "c1-2",
                name: 3,
                children: [
                  {
                    id: "c1-2-1",
                    label: "c1-2-1",
                    name: 4
                  },
                  {
                    id: "c1-2-2",
                    label: "c1-2-2",
                    name: 4
                  }
                ]
              }
            ]
          },
          {
            id: "c2",
            label: "c2",
            name: 2
          },
          {
            id: "c3",
            label: "c3",
            name: 2,

            children: [
              {
                id: "c3-1",
                label: "c3-1",
                name: 3
              },
              {
                id: "c3-2",
                label: "c3-2",
                name: 3,

                children: [
                  {
                    id: "c3-2-1",
                    label: "c3-2-1",
                    name: 4
                  },
                  {
                    id: "c3-2-2",
                    label: "c3-2-2",
                    name: 4
                  },
                  {
                    id: "c3-2-3",
                    label: "c3-2-3",
                    name: 4
                  }
                ]
              },
              {
                id: "c3-3",
                label: "c3-3",
                name: 3
              }
            ]
          }
        ]
      },
    };
  },
  mounted() {
    this.render(); //注意渲染
  },
  methods: {
    render() {
      const defaultStateStyles = {
        hover: {
          stroke: "#1890ff",
          lineWidth: 2
        }
      };
      const defaultNodeStyle = {
        fill: "#F3F7FF",
        stroke: "#3759B0",
        radius: 5
      };
      const defaultEdgeStyle = {
        stroke: "#91d5ff",
        endArrow: {
          path: "M 0,0 L 12, 6 L 9,0 L 12, -6 Z",
          fill: "#91d5ff",
          d: -20
        }
      };
      const defaultLabelCfg = {
        style: {
          fill: "#000",
          fontSize: 12
        }
      };
      const defaultLayout = {
        type: "compactBox",
        direction: "LR",
        getId: function getId(d) {
          return d.id;
        },
        getHeight: function getHeight() {
          return 16;
        },
        getWidth: function getWidth() {
          return 16;
        },
        getVGap: function getVGap() {
          return 40;
        },
        getHGap: function getHGap() {
          return 70;
        }
      };
      const width = document.getElementById("container").scrollWidth;
      const height = document.getElementById("container").scrollHeight || 450;
      this.graph = new G6.TreeGraph({
        container: "container",
        width: width,
        height: height,
        linkCenter: true,
        modes: {
          default: ["drag-canvas", "zoom-canvas"]
        },
        defaultNode: {
          type: "icon-node",
          size: [120, 40],
          style: defaultNodeStyle,
          labelCfg: defaultLabelCfg
        },
        defaultEdge: {
          type: "cubic-horizontal",
          style: {
            stroke: "#A3B1BF"
          }
        },
        nodeStateStyles: defaultStateStyles,
        edgeStateStyles: defaultStateStyles,
        layout: defaultLayout
      });
      //节点双击事件,这里的编辑页面用的是浏览器的弹窗,也可自己编写页面进行调用
      this.graph.on('node:dblclick', (evt,element) => {
          console.log(evt,element)
          const { item, target } = evt
          console.log(evt)
          const targetType = target.get('type')
          const name = target.get('name')
          console.log(target)
          var str=prompt("随便写点儿啥吧",target.attrs.text);
        })
      this.graph.on('node:click', evt => {
          const { item, target } = evt
          const targetType = target.get('type')
          const name = target.get('name')

      // 增加元素,这里增加元素也是用的浏览器的弹窗
      if (targetType === 'marker') {
        const model = item.getModel()
        if (name === 'add-item') {
          if (!model.children) {
            model.children = []
      }
          const id = 'ra';
          var str=prompt("请输入节点名称","比如c3-3-4");
      if(str){
            target.attrs.text = str
            model.children.push({
                id,
                name:1,
                label: str,
            })
          this.graph.updateChild(model, model.id)
      }
      //删除节点
        } else if (name === 'remove-item') {
          this.graph.removeChild(model.id)
        }
      }
    })
      renderMap(this.data, this.graph); //别忘了渲染
    },
  }
};
</script>

<style scoped lang="less">
@media screen and (min-width: 200px) and (max-width: 1600px) {
  #container {
    margin-top: 1%;
    height: 350px;
  }
}
@media screen and (min-width: 1601px) {
  #container {
    height: 500px;
    margin-top: 2%;
  }
}
</style>

以上内容若有问题,欢迎各位指正,共同学习~~

  • 7
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 22
    评论
Vue是一种流行的JavaScript框架,Vue 2是其第二个版本。AntV X6是一个基于Vue 2的表绘制库,可以用于绘制各种类型的表,包括树形流程。 要在Vue 2项目使用AntV X6绘制树形流程,首先需要安装和引入AntV X6库。可以通过npm或yarn进行安装: npm install @antv/x6 或者 yarn add @antv/x6 然后,可以在Vue的组件使用AntV X6。首先,引入`Graph`和`Node`组件: import { Graph, Node } from '@antv/x6-vue' 接下来,在Vue的模板添加一个`Graph`组件,并设置一些必要的属性: ``` <template> <div> <Graph :initConfig="graphConfig"> <Node :shape="nodeShape" :x="nodeX" :y="nodeY" :width="nodeWidth" :height="nodeHeight" /> </Graph> </div> </template> <script> export default { data() { return { graphConfig: { width: 800, height: 600, gridSize: 10, background: { color: '#f8f8f8' }, scroller: { enabled: true, pannable: true } }, nodeShape: 'rect', nodeX: 100, nodeY: 100, nodeWidth: 80, nodeHeight: 40 } } } </script> ``` 在上面的代码,创建了一个Graph组件和一个Node组件。Graph组件定义了整个绘区域的配置,例如大小、网格和背景颜色等。Node组件定义了一个矩形节点的形状、位置和尺寸。 通过设置Node组件的属性,可以绘制更多的节点,并使用适当的形状、位置和尺寸。 以上是一个简单的示例,展示了如何在Vue 2项目使用AntV X6绘制树形流程。通过修组件属性,可以创建更复杂的表,并通过AntV X6的其他功能来增强表的交互性和可视化效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

suoh's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值