vue3+vue-flow制作简单可拖拽可增删改流程图

实现效果

在这里插入图片描述

实现代码

准备工作

安装依赖
npm install @vue-flow/core
npm install @vue-flow/minimap //小地图
npm install @vue-flow/controls //自带的缩放、居中、加锁功能

我这里只用到上述三个,还有其余的可根据实际情况配合官方文档使用。

npm install @vue-flow/background //背景
npm install @vue-flow/node-toolbar //工具栏
npm install @vue-flow/node-resizer //缩放
创建<初始元素>js文件 initial-elements.js
import { MarkerType } from '@vue-flow/core'export const initialNodes = [{id: '1',position: { x: 100, y: 250 },type: 'custom',data: {value: '需求响应',icon1: false,icon2: false,icon3: false,icon4: false,icon5: false,},},{id: '2',position: { x: 350, y: 250 },type: 'custom',data: {value: '方案制定',icon1: false,icon2: false,icon3: false,icon4: false,icon5: false,},},{id: '3',position: { x: 600, y: 250 },type: 'custom',data: {value: '实施',icon1: false,icon2: false,icon3: false,icon4: false,icon5: false,},},{id: '4',position: { x: 850, y: 250 },type: 'custom',data: {value: '效果验证',icon1: false,icon2: false,icon3: false,icon4: false,icon5: false,},},
]export const initialEdges = [{ id: 'e1-2', source: '1', target: '2', markerEnd: MarkerType.ArrowClosed, updatable: true, EdgeMarkerType: { strokeWidth: 10 }, style: { stroke: '#999', strokeWidth: 2, strokeLinecap: 'round' } },{ id: 'e2-3', source: '2', target: '3', markerEnd: MarkerType.ArrowClosed, updatable: true, EdgeMarkerType: { strokeWidth: 10 }, style: { stroke: '#999', strokeWidth: 2, strokeLinecap: 'round' } },{ id: 'e3-4', source: '3', target: '4', markerEnd: MarkerType.ArrowClosed, updatable: true, EdgeMarkerType: { strokeWidth: 10 }, style: { stroke: '#999', strokeWidth: 2, strokeLinecap: 'round' } },
]
创建<使用拖拽>js文件 useDnD.js
import { useVueFlow } from '@vue-flow/core'
import { ref, watch } from 'vue'/*** In a real world scenario you'd want to avoid creating refs in a global scope like this as they might not be cleaned up properly.* @type {{draggedType: Ref<string|null>, isDragOver: Ref<boolean>, isDragging: Ref<boolean>}}*/
const state = {/*** The type of the node being dragged.*/draggedType: ref(null),isDragOver: ref(false),isDragging: ref(false),
}export default function useDragAndDrop() {const { draggedType, isDragOver, isDragging } = stateconst { addNodes, screenToFlowCoordinate, onNodesInitialized, updateNode } = useVueFlow()watch(isDragging, (dragging) => {document.body.style.userSelect = dragging ? 'none' : ''})function onDragStart(event, type) {console.log("onDragStart", type);if (event.dataTransfer) {event.dataTransfer.setData('application/vueflow', type)event.dataTransfer.effectAllowed = 'move'}draggedType.value = typeisDragging.value = truedocument.addEventListener('drop', onDragEnd)}/*** Handles the drag over event.** @param {DragEvent} event*/function onDragOver(event) {event.preventDefault()if (draggedType.value) {isDragOver.value = trueif (event.dataTransfer) {event.dataTransfer.dropEffect = 'move'}}}function onDragLeave() {isDragOver.value = false}function onDragEnd() {console.log("onDragEnd");isDragging.value = falseisDragOver.value = falsedraggedType.value = nulldocument.removeEventListener('drop', onDragEnd)}/*** Handles the drop event.** @param {DragEvent} event*/function onDrop(event, node) {const position = screenToFlowCoordinate({x: event.clientX,y: event.clientY,})node.position = position// /**//  * Align node position after drop, so it's centered to the mouse//  *//  * We can hook into events even in a callback, and we can remove the event listener after it's been called.//  */const { off } = onNodesInitialized(() => {updateNode(node.id, (node) => ({position: { x: node.position.x - node.dimensions.width / 2, y: node.position.y - node.dimensions.height / 2 },}))off()})addNodes(node)}return {draggedType,isDragOver,isDragging,onDragStart,onDragLeave,onDragOver,onDrop,}
}
创建<单个流程图节点>vue文件 ValueNode.vue
<template><div class="nodeItem relative"><!-- @contextmenu="handleRightClick($event, props.id)" --><!-- 开始节点的位置 --><Handle type="source" position="right" /><el-input:id="`${id}-input`"v-model="value"placeholder="点击添加文字"style="width: 170px; font-size: 14px"type="textarea"autosizemaxlength="20"resize="none"/><!-- 结束节点的位置 --><Handle type="target" position="left" /><el-icon:size="20"class="absolute red pointer"style="right: -10px; top: -10px"@click="handleDel($event, id)"><CircleCloseFilled/></el-icon></div>
</template><script setup>
import { computed } from "vue";
import { Handle, Position, useVueFlow } from "@vue-flow/core";
const { proxy } = getCurrentInstance();// 定义传递给父组件的事件
const emit = defineEmits(["updateNodes"]);
const props = defineProps(["id","data","length",
]);const { updateNodeData, removeNodes } = useVueFlow();const value = computed({get: () => props.data.value,set: (value) => {updateNodeData(props.id, { value });emit("updateNodes");},
});function handleDel(event, id) {event.preventDefault();if (props.length == 1) {proxy.$modal.msgWarning("至少保留一个节点");} else {removeNodes([id]);emit("updateNodes");}
}function handleRightClick(event, id) {console.log("右键被点击了");event.preventDefault(); // 阻止默认的右键菜单显示// 在这里可以添加更多逻辑,比如显示自定义的右键菜单等console.log("右键被点击");removeNodes([id]);
}
</script>
<style scoped lang="scss">
.nodeItem {padding: 6px 20px;background: rgba(219, 227, 247, 1);border-radius: 8px;
}
</style>

具体实现


<template><div class="w100 h100 flex1 size-15" @drop="onDrop($event, getNewNode())"><!-- <el-button @click="addNode">add</el-button> --><div class="bg-white h100 pd-16" style="width: 340px"><div class="mb-12 bold">流程图组件</div><el-buttonstyle="width: 100%; cursor: grab"plain:draggable="true"@dragstart="onDragStart($event, 'custom')">拖转至画布</el-button></div><div class="flex-1 h100"><VueFlow:key="key"ref="vueFlowRef":nodes="nodes":edges="edges"auto-connect:default-viewport="{ zoom: 1.0 }":min-zoom="0.2":max-zoom="4"@edge-update="onEdgeUpdate"@connect="onConnect"@edge-update-start="onEdgeUpdateStart"@edge-update-end="onEdgeUpdateEnd"@dragover="onDragOver"@dragleave="onDragLeave"><template #node-custom="props"><ValueNode:id="props.id":data="props.data"@updateNodes="updateNodes":length="nodes.length"/></template><MiniMap /></VueFlow></div></div>
</template><script setup>
import { ref, computed, nextTick, watch } from "vue";
import { VueFlow, useVueFlow, MarkerType } from "@vue-flow/core";
import { initialEdges, initialNodes } from "./initial-elements.js";
import { MiniMap } from "@vue-flow/minimap";
import ValueNode from "./ValueNode.vue";
import "@vue-flow/core/dist/style.css";
import "@vue-flow/core/dist/theme-default.css";const { proxy } = getCurrentInstance();import useDragAndDrop from "./useDnD.js";
import { Sunny } from "@element-plus/icons-vue";const { onDragStart, onDrop, onDragOver, onDragLeave } = useDragAndDrop();
/*** `useVueFlow` provides:* 1. a set of methods to interact with the VueFlow instance (like `fitView`, `setViewport`, `addEdges`, etc)* 2. a set of event-hooks to listen to VueFlow events (like `onInit`, `onNodeDragStop`, `onConnect`, etc)* 3. the internal state of the VueFlow instance (like `nodes`, `edges`, `viewport`, etc)*/
const {onInit,onNodeDragStop,onConnect,addEdges,updateEdge,getNodes,getEdges,
} = useVueFlow();const props = defineProps({nodes: {type: Object,default: initialNodes,},edges: {type: Object,default: initialEdges,},iconShow: {type: Object,default: () => {},},
});
const nodes = ref(null);
const edges = ref(null);const abc = "需求响应";
nodes.value = props.nodes || initialNodes;
edges.value = props.edges || initialEdges;
proxy.$emit("updateList", nodes.value, edges.value);const vueFlowRef = ref(null);
const nodeOptions = ref([]);
nodeOptions.value = handleNodesOption();// 创建一个新的节点对象
function getNewNode() {return {id: new Date().getTime().toString(),type: "custom",data: {value: "",},position: { x: 50, y: 50 },};
}// 更新节点列表
function updateNodes() {nodes.value = getNodes.value;nodeOptions.value = handleNodesOption();proxy.$emit("updateList", getNodes.value, getEdges.value);
}// 处理节点下拉数据
function handleNodesOption() {return nodes.value.filter((item) => (item.data.value ?? "") !== "").map((r) => ({label: r.data.value,value: r.data.value,}));
}/*** onNodeDragStop is called when a node is done being dragged** Node drag events provide you with:* 1. the event object* 2. the nodes array (if multiple nodes are dragged)* 3. the node that initiated the drag* 4. any intersections with other nodes*/
onNodeDragStop(({ event, nodes, node }) => {console.log("Node Drag Stop", { event, nodes, node });
});function onEdgeUpdateStart(edge) {console.log("start update", edge);
}function onEdgeUpdateEnd(edge) {console.log("end update", edge);
}function onEdgeUpdate({ edge, connection }) {console.log("onEdgeUpdate", edge, connection);updateEdge(edge, connection);console.log("onEdgeUpdate", getEdges.value);
}/*** onConnect is called when a new connection is created.** You can add additional properties to your new edge (like a type or label) or block the creation altogether by not calling `addEdges`*/
onConnect((connection) => {console.log("onConnect", connection, [connection]);const newEdges = {...connection,markerEnd: MarkerType.ArrowClosed,updatable: true,style: { stroke: "#999", strokeWidth: 2, strokeLinecap: "round" },};addEdges([newEdges]);console.log("onConnect", getEdges.value);
});watchEffect(() => {nodes.value = props.nodes || initialNodes;edges.value = props.edges || initialEdges;proxy.$emit("updateList", nodes.value, edges.value);
});function multipleChange(keyArr, type) {console.log(keyArr, type);nodes.value.forEach((node) => {let item = keyArr.find((r) => r === node.data.value);node.data[type] = item ? true : false;});console.log(nodes.value);
}
const key = ref(0);
// 重新生成
const init = (nodeArr, edgeArr) => {edges.value = edgeArr || initialEdges;nodes.value = nodeArr || initialNodes;key.value++;
};// 下一步前的校验
const checkNodesEdges = () => {console.log("checkNodesEdges", getEdges.value);let hasNoTarget = getEdges.value.length < getNodes.value.length - 1;if (hasNoTarget) {proxy.$modal.msgWarning("画布中存在节点未连线");return false;} else {proxy.$emit("updateList", getNodes.value, getEdges.value);return true;}
};// 使用defineExpose暴露方法给父组件
defineExpose({checkNodesEdges,init,
});
</script><style scoped>
:deep(.vue-flow__handle) {width: 12px !important;height: 12px !important;border: 1px solid #666 !important;background: #fff !important;
}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/bicheng/92466.shtml
繁体地址,请注明出处:http://hk.pswp.cn/bicheng/92466.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

itextPdf获取pdf文件宽高不准确

正常情况下我们通过下面方式获取宽高PdfReader reader new PdfReader(file.getPath()); float width reader.getPageSize(1).getWidth(); float height reader.getPageSize(1).getHeight();但是这样获取的宽高是不准确的&#xff0c;永远都是 宽 > 高&#xff0c;也就是横…

NodeJs学习日志(2):windows安装使用node.js 安装express,suquelize,mysql,nodemon

windows安装使用node.js 安装express&#xff0c;suquelize&#xff0c;mysql&#xff0c;nodemon 系统是win10&#xff0c;默认已经安装好nodejs与npm包名作用expressWeb应用框架suquelize数据库ORMmysql数据库nodemon代码热重载安装express 添加express生成器 npm add expres…

VueCropper 图片裁剪组件在Vue项目中的实践应用

VueCropper 图片裁剪组件在Vue项目中的实践应用 1. 组件介绍 VueCropper 是一个基于 Vue.js 的图片裁剪组件&#xff0c;它提供了丰富的图片裁剪功能&#xff0c;包括&#xff1a; 图片缩放、旋转、移动固定比例裁剪高质量图片输出多种裁剪模式选择 2. 安装与引入 首先需要安装…

给同一个wordpress网站绑定多个域名的实现方法

在WordPress网站上绑定多个域名&#xff0c;可以通过以下几种方法实现&#xff1a; 1. 修改wp-config.php文件 在wp-config.php文件中&#xff0c;找到define(‘WP_DEBUG’, false);&#xff0c;在其下方添加以下代码&#xff1a; define(WP_SITEURL, http:// . $_SERVER[HT…

HarmonyOS分布式开发实战:打造跨设备协同应用

&#x1f4d6; 文章目录 第一章&#xff1a;HarmonyOS分布式架构揭秘第二章&#xff1a;跨设备协同的核心技术第三章&#xff1a;开发环境搭建与配置第四章&#xff1a;实战项目&#xff1a;智能家居控制系统第五章&#xff1a;数据同步与状态管理第六章&#xff1a;性能优化与…

用 Enigma Virtual Box 把 Qt 程序压成单文件 EXE——从编译、收集依赖到一键封包

关键词&#xff1a;Qt、windeployqt、Enigma Virtual Box、单文件、绿色软件 为什么要打成单文件&#xff1f; 传统做法&#xff1a;用 windeployqt 把依赖拷进 release 目录&#xff0c;发给用户一个文件夹&#xff0c;文件又多又乱。理想做法&#xff1a;把整个目录压成一个…

unity中实现选中人物脚下显示圆形标识且完美贴合复杂地形(如弹坑) 的效果

要实现人物脚下圆形 完美贴合复杂地形&#xff08;如弹坑&#xff09; 的效果&#xff0c;核心思路是 「动态生成贴合地面的 Mesh」 —— 即根据地面的高度场实时计算环形顶点的 Y 坐标&#xff0c;让每个顶点都 “贴” 在地面上。核心逻辑&#xff1a;确定环形范围&#xff1a…

引领GameFi 2.0新范式:D.Plan携手顶级财经媒体启动“龙珠创意秀”

在GameFi赛道寻求新突破的今天&#xff0c;一个名为Dragonverse Plan&#xff08;D.Plan&#xff09;的项目正以其独特的经济模型和宏大愿景&#xff0c;吸引着整个Web3社区的目光。据悉&#xff0c;D.Plan即将联合中文区顶级加密媒体金色财经与非小号&#xff08;Feixiaohao&a…

通信算法之307:fpga之时序图绘制

时序图绘制软件 一. 序言 在FPGA设计过程中&#xff0c;经常需要编写设计文档&#xff0c;其中&#xff0c;不可缺少的就是波形图的绘制&#xff0c;可以直接截取Vivado或者Modelsim平台实际仿真波形&#xff0c;但是往往由于信号杂乱无法凸显重点。因此&#xff0c;通过相应软…

计网学习笔记第3章 数据链路层(灰灰题库)

题目 11 单选题 下列说法正确的是______。 A. 路由器具有路由选择功能&#xff0c;交换机没有路由选择功能 B. 三层交换机具有路由选择功能&#xff0c;二层交换机没有路由选择功能 C. 三层交换机适合异构网络&#xff0c;二层交换机不适合异构网络 D. 路由器适合异构网络&…

SQL的LEFT JOIN优化

原sql&#xff0c;一个base表a,LEFT JOIN三个表抽数 SELECT ccu.*, ctr.*, om.*, of.* FROM ods.a ccu LEFT JOIN ods.b ctr ON ccu.coupon_code ctr.coupon_code AND ctr.is_deleted 0 LEFT JOIN ods.c om ON ctr.bill_code om.order_id AND om.deleted 0 LEFT JOIN ods.…

Redis 核心概念、命令详解与应用实践:从基础到分布式集成

目录 1. 认识 Redis 2. Redis 特性 2.1 操作内存 2.2 速度快 2.3 丰富的功能 2.4 简单稳定 2.5 客户端语言多 2.6 持久化 2.7 主从复制 2.8 高可用 和 分布式 2.9 单线程架构 2.9.1 引出单线程模型 2.9.2 单线程快的原因 2.10 Redis 和 MySQL 的特性对比 2.11 R…

【Day 18】Linux-DNS解析

目录 一、DNS概念 1、概念和作用 2、域名解析类型 3、 软件与服务 4、DNS核心概念 区域 记录 5、查询类型 6、分层结构 二、DNS操作 配置本机为DNS内网解析服务器 &#xff08;1&#xff09;修改主配置文件 &#xff08;2&#xff09;添加区域 正向解析区域&#xff1a; …

Python 中 OpenCV (cv2) 安装与使用介绍

Python 中 OpenCV (cv2) 安装与使用详细指南 OpenCV (Open Source Computer Vision Library) 是计算机视觉领域最流行的库之一。Python 通过 cv2 模块提供 OpenCV 的接口。 一、安装 OpenCV 方法 1&#xff1a;基础安装&#xff08;推荐&#xff09; # 安装核心包&#xff0…

微软WSUS替代方案

微软WSUS事件回顾2025年7月10日&#xff0c;微软最新确认Windows Server Update Services&#xff08;WSUS&#xff09;出现了问题&#xff0c;导致IT管理员无法正常同步和部署Windows更新。WSUS是允许管理员根据策略配置&#xff0c;将更新推送到特定计算机&#xff0c;并优化…

Minio 分布式集群安装配置

目录创建 mkdir -p /opt/minio/run && mkdir -p /etc/minio && mkdir -p /indata/disk_0/minio/datarun&#xff1a;启动脚本及二进制文件目录/etc/minio&#xff1a;配置文件目录data&#xff1a;数据存储目录下载 minio wget https://dl.min.io/server/minio…

Spring Boot + ShardingSphere 实现分库分表 + 读写分离实战

&#x1f680; Spring Boot ShardingSphere 实现分库分表 读写分离&#xff08;涵盖99%真实场景&#xff09; &#x1f3f7;️ 标签&#xff1a;ShardingSphere、分库分表、读写分离、MySQL 主从、Spring Boot 实战 分库分表 vs 读写分离 vs 主从配置与数据库高可用架构区别 …

将普通用户添加到 Docker 用户组

这样可以避免每次使用 Docker 命令时都需要 sudo。以下是具体步骤&#xff1a;1. 创建 Docker 用户组&#xff08;如果尚未存在&#xff09; 默认情况下&#xff0c;安装 Docker 时会自动创建 docker 用户组。可以通过以下命令检查&#xff1a; groupadd docker&#xff08;如果…

Scrapy(一):轻松爬取图片网站内容​

目录 一、CrawlSpider 简介​ 二、实战案例&#xff1a;图片网站爬取​ 三、代码解析&#xff1a;核心组件详解​ 类定义&#xff1a; 2.核心属性&#xff1a;​ 3.爬取规则&#xff08;Rules&#xff09;&#xff1a;​ 4.数据提取方法&#xff08;parse_item&#xff09;…

使用 systemd 的原生功能来实现 Redis 的自动监控和重启,而不是依赖额外的脚本最佳实践方案

使用 systemd 的原生功能来实现 Redis 的自动监控和重启&#xff0c;而不是依赖额外的脚本最佳实践方案方案 1&#xff1a;配置 systemd 服务文件&#xff08;推荐&#xff09;1. 检查/创建 Redis 的 systemd 服务文件2. 配置关键参数&#xff08;覆盖配置示例&#xff09;3. 重…