>  기사  >  웹 프론트엔드  >  Vue를 사용하여 순서도를 만드는 방법은 무엇입니까?

Vue를 사용하여 순서도를 만드는 방법은 무엇입니까?

WBOY
WBOY원래의
2023-06-25 09:16:433864검색

인터넷이 발전함에 따라 작업 흐름 차트, 회로도 등과 같은 흐름 차트 생성이 필요한 응용 프로그램이 점점 더 많아지고 있습니다. 매우 인기 있는 프런트 엔드 프레임워크인 Vue.js는 뛰어난 상호 작용성과 유지 관리성을 제공하므로 복잡한 순서도 애플리케이션을 구축하는 데 널리 사용됩니다.

이 기사에서는 다음 단계를 포함하여 Vue를 사용하여 순서도 생성을 구현하는 방법을 소개합니다.

  1. 필요한 종속성 설치
  2. 기본 구성 요소 구조 작성
  3. 드래그 앤 드롭 기능 구현
  4. 연결선 구현
  5. 노드 편집 구현
  6. Export Flowchart
  7. 필요한 종속성 설치

먼저 vue-draggable-resizing 라이브러리를 설치해야 합니다. 이는 드래그 및 드래그를 실현할 수 있는 매우 사용하기 쉬운 Vue 플러그인입니다. 요소의 줌 기능. npm 설치를 사용할 수 있습니다.

npm install vue-draggable-resizable --save
  1. 기본 구성 요소 구조 작성

플로우 차트 편집을 구현하려면 Vue 구성 요소를 사용해야 합니다. 모든 순서도 요소가 포함된 FlowChart 구성 요소를 만들어야 합니다. 각 노드는 순서도의 단계를 나타내는 노드 구성 요소입니다. 연결선은 서로 다른 노드를 연결하는 데 사용되는 연결 구성 요소입니다.

먼저 모든 노드와 연결선을 포함하기 위해 FlowChart.vue 파일에 추상 FlowChart 구성 요소를 만들어야 합니다.

<template>
  <div class="flowchart">
    <div class="nodes">
      <!-- 组件插槽,用于插入节点 -->
      <slot name="nodes"></slot>
    </div>
    <svg class="connections">
      <!-- 组件插槽,用于插入连接线 -->
      <slot name="connections"></slot>
    </svg>
  </div>
</template>

<script>
export default {
  name: 'FlowChart'
}
</script>

FlowChart 구성 요소의 두 슬롯에 노드와 연결 선을 각각 배치합니다.

다음으로 순서도의 노드와 연결선을 나타내기 위해 Node 및 Connection 구성 요소를 만들어야 합니다.

Node.vue:

<template>
  <draggable-resizable :w="width" :h="height" :x="x" :y="y">
    <div class="node">
      <!-- 节点的内容 -->
      <div class="node-content">
        <slot></slot>
      </div>
    </div>
  </draggable-resizable>
</template>

<script>
import VueDraggableResizable from 'vue-draggable-resizable'

export default {
  name: 'Node',
  components: {
    VueDraggableResizable
  },
  props: {
    width: {
      type: Number,
      default: 100
    },
    height: {
      type: Number,
      default: 50
    },
    x: {
      type: Number,
      default: 0
    },
    y: {
      type: Number,
      default: 0
    }
  }
}
</script>

Connection.vue:

<template>
  <svg class="connection">
    <!-- SVG 路径元素,用于绘制连接线 -->
    <path :d="path"></path>
  </svg>
</template>

<script>
export default {
  name: 'Connection',
  props: {
    start: Object,
    end: Object
  },
  computed: {
    path () {
      // 计算连接线的路径
      const startX = this.start.x + this.start.width / 2
      const startY = this.start.y + this.start.height / 2
      const endX = this.end.x + this.end.width / 2
      const endY = this.end.y + this.end.height / 2
      return `M ${startX} ${startY} L ${endX} ${endY}`
    }
  }
}
</script>

vue-draggable-ressible 구성 요소를 사용하여 구현 노드를 드래그하고 크기를 조정하려면 노드의 너비, 높이, x, y 및 기타 속성을 전달해야 합니다. 연결선은 SVG의 path 요소를 이용하여 그려지며, 노드의 위치와 크기에 따라 경로를 계산해야 합니다.

  1. 드래그 앤 드롭 기능 구현

노드의 드래그 앤 드롭 기능을 구현하려면 Node 컴포넌트에 v-on:drag, v-on:dragstop 및 v-on:resize 이벤트 리스너를 추가해야 합니다. . 이는 각각 드래그, 드래그 종료 및 노드 크기 조정에 해당합니다.

<draggable-resizable
  :w="width"
  :h="height"
  :x="x"
  :y="y"
  v-on:drag="onDrag"
  v-on:dragstop="onDragStop"
  v-on:resize="onResize"
>
  <!-- 节点的内容 -->
</draggable-resizable>

<script>
export default {
  name: 'Node',
  methods: {
    onDrag (pos) {
      // 拖拽事件处理函数
      this.$emit('move', {
        x: pos.x,
        y: pos.y
      })
    },
    onDragStop (pos) {
      // 结束拖拽事件处理函数
      this.$emit('endMove', {
        x: pos.x,
        y: pos.y
      })
    },
    onResize (size) {
      // 调整大小事件处理函数
      this.$emit('resize', {
        width: size.width,
        height: size.height
      })
    }
  }
}
</script>

노드 위치와 크기의 실시간 업데이트를 달성하기 위해 이러한 이벤트 처리 함수에서 $emit 메서드를 통해 상위 구성 요소에 이벤트를 보냅니다. FlowChart 구성 요소에서는 다음 이벤트를 수신하고 노드 정보를 업데이트해야 합니다.

<template>
  <div class="flowchart">
    <div class="nodes">
      <!-- 将节点插入到插槽中 -->
      <slot name="nodes"></slot>
    </div>
    <svg class="connections">
      <!-- 将连接线插入到插槽中 -->
      <slot name="connections"></slot>
      <!-- 鼠标跟随的连接线 -->
      <Connection v-if="showConnection"
                  :start="{x: start.x + start.width / 2, y: start.y + start.height / 2, width: start.width, height: start.height}"
                  :end="{x: end.x + end.width / 2, y: end.y + end.height / 2, width: end.width, height: end.height}"/>
    </svg>
  </div>
</template>

<script>
import Node from './Node.vue'
import Connection from './Connection.vue'

export default {
  name: 'FlowChart',
  components: {
    Node,
    Connection
  },
  data () {
    return {
      showConnection: false,
      start: null, // 起点节点
      end: null // 终点节点
    }
  },
  methods: {
    onNodeMove (node, pos) {
      // 节点拖拽时的事件处理函数
      node.x = pos.x
      node.y = pos.y
    },
    onNodeEndMove (node, pos) {
      // 节点结束拖拽时的事件处理函数
      node.x = pos.x
      node.y = pos.y
      this.showConnection = false
      this.start = null
      this.end = null
    },
    onNodeResize (node, size) {
      // 节点调整大小时的事件处理函数
      node.width = size.width
      node.height = size.height
    },
    connectNodes (start, end) {
      // 连接两个节点
      this.showConnection = true
      this.start = start
      this.end = end
    }
  }
}
</script>

노드 끌기, 끌기 종료 및 크기 조정에 응답하기 위해 onNodeMove, onNodeEndMove 및 onNodeResize 세 가지 이벤트 처리 함수를 정의했습니다. connectNodes 함수는 두 노드를 연결하는 데 사용됩니다.

  1. 연결선 구현

FlowChart 컴포넌트에서는 연결선의 정보를 저장하기 위해 showConnection 변수와 start 및 end 두 개의 변수를 정의합니다. 연결선을 그리려면 마우스 이벤트를 통해 이 정보를 업데이트해야 합니다.

먼저 Node 구성 요소에 v-on:mousedown 및 v-on:mouseup 이벤트에 대한 수신 대기를 추가해야 합니다. 이러한 이벤트는 사용자가 노드를 선택했는지 여부를 감지하는 데 사용됩니다.

<draggable-resizable
  :w="width"
  :h="height"
  :x="x"
  :y="y"
  v-on:drag="onDrag"
  v-on:dragstop="onDragStop"
  v-on:resize="onResize"
  v-on:mousedown="onMouseDown"
  v-on:mouseup="onMouseUp"
>
  <!-- 节点的内容 -->
</draggable-resizable>

<script>
export default {
  name: 'Node',
  methods: {
    ...
    onMouseDown () {
      // 鼠标按下时选中当前节点
      this.$emit('select', this)
    },
    onMouseUp () {
      // 鼠标松开时取消选中
      this.$emit('unselect')
    }
  }
}
</script>

현재 노드를 선택하기 위해 onMouseDown 이벤트 핸들러 함수의 상위 구성 요소에 선택 이벤트를 보냅니다. FlowChart 구성 요소에서는 다음 이벤트를 수신해야 합니다.

<template>
  <div class="flowchart">
    <div class="nodes">
      <!-- 将节点插入到插槽中 -->
      <slot name="nodes"></slot>
    </div>
    <svg class="connections">
      <!-- 将连接线插入到插槽中 -->
      <slot name="connections"></slot>
      <!-- 鼠标跟随的连接线 -->
      <Connection v-if="showConnection"
                  :start="{x: start.x + start.width / 2, y: start.y + start.height / 2, width: start.width, height: start.height}"
                  :end="{x: end.x + end.width / 2, y: end.y + end.height / 2, width: end.width, height: end.height}"/>
    </svg>
  </div>
</template>

<script>
import Node from './Node.vue'
import Connection from './Connection.vue'

export default {
  name: 'FlowChart',
  components: {
    Node,
    Connection
  },
  data () {
    return {
      showConnection: false,
      start: null, // 起点节点
      end: null // 终点节点
    }
  },
  methods: {
    ...
    onSelectNode (node) {
      // 选中节点时的事件处理函数
      if (this.start) {
        // 已选择起点,连接当前节点
        this.end = node
        this.connectNodes(this.start, this.end)
      } else {
        // 选择起点
        this.start = node
      }
    },
    onUnselectNode () {
      // 取消选中节点时的事件处理函数
      this.start = null
      this.end = null
      this.showConnection = false
    }
  }
}
</script>

onSelectNode 이벤트 핸들러 함수에서 현재 시작점 노드가 선택되어 있는지 확인하고, 그렇다면 현재 노드를 연결합니다. 그렇지 않으면 현재 노드를 출발점. onUnselectNode 이벤트 핸들러에서 노드 선택을 취소하고 연결선 정보를 재설정합니다.

  1. 노드 편집 실현

노드 편집을 구현하려면 Node.vue에 편집 버튼을 추가하고 클릭 이벤트를 수신해야 합니다.

<template>
  <draggable-resizable ...>
    <div class="node">
      <div class="node-content" v-on:click="$emit('edit')">
        <!-- 节点的内容 -->
      </div>
      <button class="edit-button" v-on:click="$emit('edit')">
        编辑
      </button>
    </div>
  </draggable-resizable>
</template>

<script>
export default {
  name: 'Node'
}
</script>

<style>
.edit-button {
  position: absolute;
  bottom: 5px;
  right: 5px;
}
</style>

그런 다음 FlowChart.vue에서 편집 이벤트를 수신하고 select Display an input box on the node:

<template>
  <div class="flowchart">
    <div class="nodes">
      <!-- 将节点插入到插槽中 -->
      <slot name="nodes"></slot>
    </div>
    <svg class="connections">
      <!-- 将连接线插入到插槽中 -->
      <slot name="connections"></slot>
      <!-- 鼠标跟随的连接线 -->
      <Connection v-if="showConnection"
                  :start="{x: start.x + start.width / 2, y: start.y + start.height / 2, width: start.width, height: start.height}"
                  :end="{x: end.x + end.width / 2, y: end.y + end.height / 2, width: end.width, height: end.height}"/>
    </svg>

    <!-- 编辑区域 -->
    <div class="edit-panel" v-if="selectedNode">
      <h3>编辑节点</h3>
      <form v-on:submit.prevent="saveNode">
        <label for="node-label">节点名称</label>
        <input id="node-label" type="text" v-model="nodeLabel">
        <button type="submit">保存</button>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FlowChart',
  data () {
    return {
      showConnection: false,
      start: null, // 起点节点
      end: null, // 终点节点
      selectedNode: null, // 选中的节点
      nodeLabel: '' // 当前节点的标签
    }
  },
  methods: {
    ...
    onSelectNode (node) {
      // 选中节点时的事件处理函数
      if (this.start) {
        // 已选择起点,连接当前节点
        this.end = node
        this.connectNodes(this.start, this.end)
        this.selectedNode = null
      } else {
        // 选择起点
        this.start = node
      }
    },
    onUnselectNode () {
      // 取消选中节点时的事件处理函数
      this.start = null
      this.end = null
      this.showConnection = false
      this.selectedNode = null
    },
    onEditNode (node) {
      // 编辑节点时的事件处理函数
      this.selectedNode = node
      this.nodeLabel = node.$slots.default[0].text.trim()
    },
    saveNode () {
      // 保存节点编辑后的信息
      this.selectedNode.$slots.default[0].text = this.nodeLabel
      this.selectedNode = null
    }
  }
}
</script>

<style>
.edit-panel {
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
  height: 100%;
  background: #fff;
  padding: 20px;
  box-shadow: -1px 0 10px rgba(0, 0, 0, 0.3);
}
</style>

노드 편집 상자를 숨기기 위해 onSelectNode 이벤트 핸들러 함수에 this.selectedNode = null을 추가했습니다. onEditNode 이벤트 핸들러에서는 선택한 노드를 편집하기 위한 입력 상자를 표시하기 위해 상위 구성 요소에 편집 이벤트를 보냅니다. saveNode 이벤트 핸들러 함수에 노드의 편집된 정보를 저장합니다.

  1. 흐름도 내보내기

마지막으로 FlowChart.vue에 내보내기 버튼을 추가하여 현재 흐름도를 JSON 형식으로 내보낼 수 있습니다.

<template>
  <div class="flowchart">
    <div class="nodes">
      <!-- 将节点插入到插槽中 -->
      <slot name="nodes"></slot>
    </div>
    <svg class="connections">
      <!-- 将连接线插入到插槽中 -->
      <slot name="connections"></slot>
      <!-- 鼠标跟随的连接线 -->
      <Connection v-if="showConnection"
                  :start="{x: start.x + start.width / 2, y: start.y + start.height / 2, width: start.width, height: start.height}"
                  :end="{x: end.x + end.width / 2, y: end.y + end.height / 2, width: end.width, height: end.height}"/>
    </svg>

    <!-- 编辑区域 -->
    ...

    <!-- 导出按钮 -->
    <button class="export-button" v-on:click="exportFlowchart">导出</button>
  </div>
</template>

<script>
export default {
  name: 'FlowChart',
  methods: {
    ...
    exportFlowchart () {
      // 导出流程图
      const nodes = []
      const connections = []
      this.$slots.nodes.forEach(vnode => {
        const node = vnode.componentInstance
        nodes.push({
          x: node.x,
          y: node.y,
          width: node.width,
          height: node.height,
          label: node.$slots.default[0].text.trim()
        })
      })

위 내용은 Vue를 사용하여 순서도를 만드는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.