Vue 3 + jsPlumb:从零构建企业级可视化流程编排器
你是否曾面对过这样的需求:产品经理递来一份复杂的业务流程图,要求你在两周内实现一个可交互、可配置、还能保存和加载的流程设计器?面对琳琅满目的图表库,从 AntV X6 到 G6,再到 React Flow,选择似乎很多,但上手成本、定制灵活度和与 Vue 3 的契合度,往往让人犹豫不决。
今天,我们不谈那些庞大而复杂的框架,而是聚焦于一个经典且轻量的选择——jsPlumb。结合 Vue 3 的响应式与组合式 API,我们不仅能快速搭建出功能强大的流程图,更能深入其内核,打造一个真正属于自己业务的可视化编排工具。这篇文章将带你绕过那些官方文档里语焉不详的“坑”,直接进入实战,用清晰的步骤和可落地的代码,构建一个支持拖拽生成、规则连接、样式定制、JSON序列化乃至画布协同的流程编辑器。
1. 环境搭建与核心架构设计
在开始写第一行代码之前,我们需要明确目标:我们要构建的不是一个简单的静态图表,而是一个动态的、数据驱动的流程编排器。这意味着,画布上的每一个节点、每一条连线,都是应用内部状态的可视化映射。
1.1 技术选型与初始化
首先,创建一个标准的 Vue 3 项目。这里我们使用 Vite 以获得更快的启动和热更新体验。
npm create vue@latest vue-flow-editor
cd vue-flow-editor
npm install
接着,安装核心依赖:
npm install jsplumb @vueuse/core lodash-es
为什么是这三个?
- jsPlumb (Community Edition): 核心连线库,轻量、API 稳定,社区版足够满足绝大多数流程图需求。
- @vueuse/core: 提供一系列实用的 Vue 3 组合式工具函数,如
useLocalStorage、useEventListener,能极大提升开发效率。 - lodash-es: 提供可靠的工具函数,如
cloneDeep,throttle,处理数据更安全高效。
项目结构规划如下,这有助于保持代码的清晰和可维护性:
src/
├── components/
│ ├── FlowEditor.vue # 主编辑器组件
│ ├── FlowNode.vue # 可复用的节点组件
│ ├── Toolbar.vue # 顶部工具栏
│ └── Sidebar.vue # 左侧节点面板
├── composables/ # 组合式函数
│ ├── useJsPlumb.ts # jsPlumb实例管理与核心逻辑
│ ├── useFlowData.ts # 流程图数据状态管理
│ └── useKeyboard.ts # 键盘快捷键管理
├── types/
│ └── flow.ts # TypeScript类型定义
└── utils/
└── export.ts # 导入导出工具函数
1.2 定义核心数据模型
一切可视化的基础是数据。在 types/flow.ts 中,我们定义流程图的核心数据结构:
// 节点类型枚举
export enum NodeType {
START = 'start',
PROCESS = 'process',
DECISION = 'decision',
END = 'end',
CUSTOM = 'custom'
}
// 节点数据接口
export interface FlowNode {
id: string; // 唯一标识,使用 nanoid 或 uuid 生成
type: NodeType;
label: string;
position: { x: number; y: number }; // 相对于画布的坐标
style: {
backgroundColor: string;
borderColor?: string;
icon?: string; // 可选的图标标识
width?: number;
height?: number;
};
// 业务数据扩展点
config?: Record<string, any>;
}
// 连线数据接口
export interface FlowConnection {
id: string;
sourceId: string; // 源节点ID
targetId: string; // 目标节点ID
sourceEndpoint?: string; // 源端点标识(如 'right')
targetEndpoint?: string; // 目标端点标识(如 'left')
label?: string; // 连线上的标签
style?: {
stroke: string;
strokeWidth: number;
dashstyle?: string; // 虚线样式,如 '5,5'
};
}
// 整个流程图的数据快照
export interface FlowData {
nodes: FlowNode[];
connections: FlowConnection[];
viewport: {
zoom: number;
pan: { x: number; y: number };
};
}
这个模型清晰地分离了视图属性(位置、样式)和业务属性(配置),为后续的序列化和反序列化打下了坚实基础。
2. jsPlumb 实例化与画布初始化
jsPlumb 的核心是一个管理连接和端点的实例。在 Vue 3 中,我们将其封装在一个组合式函数 useJsPlumb 中,实现逻辑复用与状态隔离。
2.1 创建可管理的 jsPlumb 实例
在 composables/useJsPlumb.ts 中:
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { jsPlumb, jsPlumbInstance } from 'jsplumb';
import type { FlowNode, FlowConnection } from '@/types/flow';
export function useJsPlumb(containerRef: Ref<HTMLElement | undefined>) {
const instance = ref<jsPlumbInstance | null>(null);
const isReady = ref(false);
const initJsPlumb = () => {
if (!containerRef.value) return;
// 销毁旧实例,避免内存泄漏
if (instance.value) {
instance.value.destroy();
}
// 创建新实例,并应用一些默认配置
const jsPlumbInstance = jsPlumb.getInstance({
container: containerRef.value,
// 使用SVG渲染,性能更好,样式更灵活
renderMode: 'svg',
// 连接器样式:贝塞尔曲线
connector: ['Bezier', { curviness: 100 }],
// 端点样式:小圆点
endpoint: ['Dot', { radius: 6 }],
// 连接点样式
paintStyle: { stroke: '#409EFF', strokeWidth: 2 },
// 悬停样式
hoverPaintStyle: { stroke: '#FF6B6B', strokeWidth: 3 },
// 连接覆盖样式
overlayStyle: { fill: '#666', fontSize: '12px' },
// 允许连接从任何端点拖出
connectionOverlays: [
['Arrow', { location: 1, width: 12, length: 12 }],
['Label', { label: '连接', location: 0.5, cssClass: 'connection-label' }]
]
});
// 使画布内的节点可拖拽
jsPlumbInstance.draggable(containerRef.value.querySelectorAll('.flow-node'), {
containment: 'parent',
// 拖拽时实时更新节点位置数据
drag: (params) => {
const nodeId = params.el.id;
// 这里可以触发一个自定义事件或调用回调,更新节点的 position 数据
console.log(`节点 ${nodeId} 被拖拽到:`, params.pos);
}
});
instance.value = jsPlumbInstance;
isReady.value = true;
return jsPlumbInstance;
};
// 在组件挂载后初始化
onMounted(() => {
nextTick(() => {
initJsPlumb();
});
});
// 在组件卸载前清理
onUnmounted(() => {
if (instance.value) {
instance.value.reset();
instance.value = null;
}
});
return {
instance,
isReady,
initJsPlumb
};
}
关键提示:
jsPlumb.getInstance()是获取实例的标准方式。务必在组件卸载时调用reset()或destroy()来清理事件监听和DOM引用,这是避免内存泄漏的关键。
2.2 构建可拖拽的节点组件
节点是流程图的原子单元。我们创建一个 FlowNode.vue 组件,它不仅是视觉呈现的载体,更是交互的入口。
<!-- FlowNode.vue -->
<template>
<div
:id="node.id"
class="flow-node"
:style="nodeStyle"
@mousedown="onMouseDown"
@contextmenu.prevent="onContextMenu"
>
<!-- 节点图标区域 -->
<div class="node-icon" :style="{ color: iconColor }">
<i :class="iconClass" v-if="iconClass"></i>
<span v-else>{{ node.type.charAt(0).toUpperCase() }}</span>
</div>
<!-- 节点标签 -->
<div class="node-label" @dblclick="onLabelDblClick">
{{ node.label }}
</div>
<!-- 连接端点:左右各一个 -->
<div class="endpoint source" data-endpoint="right"></div>
<div class="endpoint target" data-endpoint="left"></div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import type { FlowNode } from '@/types/flow';
const props = defineProps<{
node: FlowNode;
}>();
const emit = defineEmits<{
'update:position': [position: { x: number; y: number }];
'node-click': [node: FlowNode];
'node-contextmenu': [node: FlowNode, event: MouseEvent];
}>();
// 动态计算节点样式
const nodeStyle = computed(() => ({
left: `${props.node.position.x}px`,
top: `${props.node.position.y}px`,
backgroundColor: props.node.style.backgroundColor,
borderColor: props.node.style.borderColor || '#ddd',
width: props.node.style.width ? `${props.node.style.width}px` : '120px',
height: props.node.style.height ? `${props.node.style.height}px` : '60px'
}));
// 根据节点类型映射图标
const iconClass = computed(() => {
const map: Record<string, string> = {
'start': 'icon-play-circle',
'process': 'icon-gear',
'decision': 'icon-question-circle',
'end': 'icon-check-circle',
'custom': 'icon-cube'
};
return map[props.node.type] || '';
});
const iconColor = computed(() => {
// 可以根据节点状态或类型返回不同颜色
return '#fff';
});
const onMouseDown = (e: MouseEvent) => {
// 阻止事件冒泡,避免与画布拖拽冲突
e.stopPropagation();
emit('node-click', props.node);
};
const onContextMenu = (e: MouseEvent) => {
emit('node-contextmenu', props.node, e);
};
const onLabelDblClick = () => {
// 触发标签编辑,可以弹出一个输入框
const newLabel = prompt('请输入节点名称', props.node.label);
if (newLabel !== null) {
// 这里应通过状态管理更新节点数据
console.log('更新标签为:', newLabel);
}
};
</script>
<style scoped>
.flow-node {
position: absolute;
border-radius: 8px;
border: 2px solid;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: move;
user-select: none;
transition: box-shadow 0.2s;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.flow-node:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
z-index: 10;
}
.node-icon {
font-size: 20px;
margin-bottom: 4px;
}
.node-label {
font-size: 14px;
font-weight: 500;
color: #333;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 8px;
}
/* 连接端点样式 */
.endpoint {
position: absolute;
width: 12px;
height: 12px;
border-radius: 50%;
background-color: #fff;
border: 2px solid #409EFF;
opacity: 0;
transition: opacity 0.2s;
}
.flow-node:hover .endpoint {
opacity: 1;
}
.endpoint.source {
right: -6px;
top: 50%;
transform: translateY(-50%);
}
.endpoint.target {
left: -6px;
top: 50%;
transform: translateY(-50%);
}
</style>
这个组件实现了节点的基本外观、交互反馈(悬停、点击)以及为后续连线准备的端点占位。注意,端点的实际创建和连线管理应由 jsPlumb 实例在节点挂载到DOM后完成。
3. 实现动态连线与连接规则
连线是流程图的灵魂。jsPlumb 提供了强大的连接管理能力,但我们需要在其基础上增加业务规则,例如:开始节点不能有入线、结束节点不能有出线、决策节点最多只能有两个出线(是/否)。
3.1 建立连接与端点管理
在 useJsPlumb 组合式函数中,我们扩展连接管理功能:
// 在 useJsPlumb.ts 中继续扩展
export function useJsPlumb(containerRef: Ref<HTMLElement | undefined>) {
// ... 之前的代码
// 为指定节点添加可连接的端点
const makeNodeConnectable = (nodeId: string, nodeType: NodeType) => {
if (!instance.value) return;
const sourceAnchors = ['Right'];
const targetAnchors = ['Left'];
// 根据节点类型调整连接规则
switch (nodeType) {
case NodeType.START:
// 开始节点:只有出口,没有入口
targetAnchors.length = 0;
break;
case NodeType.END:
// 结束节点:只有入口,没有出口
sourceAnchors.length = 0;
break;
case NodeType.DECISION:
// 决策节点:可以有两个出口(是/否)
sourceAnchors.push('Bottom'); // 增加底部出口
break;
}
// 添加入口端点
targetAnchors.forEach(anchor => {
instance.value!.addEndpoint(nodeId, {
anchor: anchor,
isTarget: true,
maxConnections: -1, // -1 表示无限连接
endpoint: ['Rectangle', { width: 10, height: 10 }]
}, {
paintStyle: { fill: '#52c41a' } // 绿色表示目标端点
});
});
// 添加出口端点
sourceAnchors.forEach(anchor => {
instance.value!.addEndpoint(nodeId, {
anchor: anchor,
isSource: true,
maxConnections: -1,
endpoint: ['Dot', { radius: 6 }]
}, {
paintStyle: { fill: '#1890ff' } // 蓝色表示源端点
});
});
};
// 监听连接建立事件,并应用业务规则
const setupConnectionListeners = () => {
if (!instance.value) return;
instance.value.bind('connection', (info: any, originalEvent?: MouseEvent) => {
const { sourceId, targetId, sourceEndpoint, targetEndpoint } = info;
console.log(`连接建立: ${sourceId} -> ${targetId}`);
// 1. 检查是否允许连接(例如,防止循环连接)
if (sourceId === targetId) {
console.warn('不允许连接自身');
instance.value!.deleteConnection(info);
return;
}
// 2. 检查连接规则(这里可以调用外部传入的验证函数)
const isValid = validateConnectionRule(sourceId, targetId);
if (!isValid) {
console.warn('连接违反业务规则');
instance.value!.deleteConnection(info);
return;
}
// 3. 连接建立成功,触发自定义事件或更新状态
const newConnection: FlowConnection = {
id: `conn_${Date.now()}`,
sourceId,
targetId,
sourceEndpoint: sourceEndpoint?.anchor.type,
targetEndpoint: targetEndpoint?.anchor.type
};
// 通过自定义事件或状态管理通知父组件
window.dispatchEvent(new CustomEvent('flow-connection-created', {
detail: newConnection
}));
});
// 监听连接被拖动(即将建立)的事件,用于实时验证
instance.value.bind('connectionDrag', (connection: any) => {
// 可以在这里实时高亮或阻止不合法的目标
console.log('正在拖动连接...');
});
};
// 一个简单的连接规则验证示例
const validateConnectionRule = (sourceId: string, targetId: string): boolean => {
// 实际项目中,这里需要根据节点类型、已有连接等复杂逻辑判断
// 例如:一个节点不能同时连接到多个相同类型的节点
return true; // 暂时全部允许
};
return {
// ... 之前的返回值
makeNodeConnectable,
setupConnectionListeners
};
}
3.2 实现连线样式与交互反馈
连线不仅仅是静态的线条,良好的交互反馈能极大提升用户体验。我们可以通过 jsPlumb 的事件系统来实现悬停高亮、点击选择等功能。
// 继续在 useJsPlumb.ts 中扩展
const setupConnectionInteractions = () => {
if (!instance.value) return;
// 连线悬停效果
instance.value.bind('connectionMouseOver', (connection: any) => {
connection.setPaintStyle({ stroke: '#ff7875', strokeWidth: 3 });
// 可以显示一个删除按钮或信息提示
const overlay = connection.getOverlay('label');
if (overlay) {
overlay.setLabel('点击删除');
}
});
instance.value.bind('connectionMouseOut', (connection: any) => {
connection.setPaintStyle({ stroke: '#409EFF', strokeWidth: 2 });
const overlay = connection.getOverlay('label');
if (overlay) {
overlay.setLabel('连接');
}
});
// 连线点击事件:删除或编辑
instance.value.bind('click', (connection: any, event: MouseEvent) => {
event.stopPropagation();
// 右键点击可能弹出菜单,左键点击可能选中
if (event.button === 2) { // 右键
// 显示上下文菜单,提供“删除连线”、“编辑标签”等选项
showConnectionContextMenu(connection, event.clientX, event.clientY);
} else {
// 选中该连线,可以高亮或显示属性面板
selectConnection(connection);
}
});
// 连线双击事件:快速编辑标签
instance.value.bind('dblclick', (connection: any) => {
const currentLabel = connection.getOverlay('label')?.getLabel() || '';
const newLabel = prompt('请输入连线标签', currentLabel);
if (newLabel !== null) {
connection.getOverlay('label')?.setLabel(newLabel);
// 更新对应的 FlowConnection 数据
updateConnectionLabel(connection.id, newLabel);
}
});
};
// 一个实用的功能:批量导入连接
const importConnections = (connections: FlowConnection[]) => {
if (!instance.value) return;
connections.forEach(conn => {
try {
instance.value!.connect({
source: conn.sourceId,
target: conn.targetId,
anchors: [conn.sourceEndpoint || 'Right', conn.targetEndpoint || 'Left'],
paintStyle: conn.style,
overlays: conn.label ? [
['Label', { label: conn.label, location: 0.5 }]
] : []
});
} catch (error) {
console.error(`导入连接失败 ${conn.sourceId} -> ${conn.targetId}:`, error);
}
});
};
通过以上代码,我们不仅实现了基础的连线功能,还增加了丰富的交互细节:悬停高亮、点击反馈、标签编辑等。这些细节是区分“能用”和“好用”的关键。
4. 节点与流程的深度定制
一个专业的流程图编辑器,必须支持对节点外观和流程行为的深度定制。这包括动态修改节点样式(颜色、图标)、配置节点属性以及实现复杂的右键菜单。
4.1 实现动态样式与属性配置
我们创建一个节点配置面板组件,当用户选中一个节点时,侧边栏会显示该节点的可配置属性。
首先,在 useFlowData.ts 中管理当前选中的节点:
// composables/useFlowData.ts
import { ref, reactive } from 'vue';
import type { FlowNode, FlowConnection } from '@/types/flow';
export function useFlowData() {
const nodes = ref<FlowNode[]>([]);
const connections = ref<FlowConnection[]>([]);
const selectedNodeId = ref<string | null>(null);
const selectedConnectionId = ref<string | null>(null);
// 获取当前选中的节点
const selectedNode = computed(() => {
return nodes.value.find(node => node.id === selectedNodeId.value) || null;
});
// 更新节点属性
const updateNodeStyle = (nodeId: string, stylePatch: Partial<FlowNode['style']>) => {
const node = nodes.value.find(n => n.id === nodeId);
if (node) {
node.style = { ...node.style, ...stylePatch };
}
};
// 更新节点业务配置
const updateNodeConfig = (nodeId: string, configPatch: Record<string, any>) => {
const node = nodes.value.find(n => n.id === nodeId);
if (node) {
node.config = { ...node.config, ...configPatch };
}
};
return {
nodes,
connections,
selectedNodeId,
selectedNode,
updateNodeStyle,
updateNodeConfig
};
}
然后,创建一个 NodePropertyPanel.vue 组件:
<!-- NodePropertyPanel.vue -->
<template>
<div class="property-panel" v-if="selectedNode">
<h3>节点属性</h3>
<!-- 基础信息 -->
<div class="property-section">
<label>节点名称</label>
<input type="text" v-model="selectedNode.label" @change="onPropertyChange" />
</div>
<!-- 样式配置 -->
<div class="property-section">
<h4>样式</h4>
<div class="style-grid">
<div>
<label>背景色</label>
<input type="color" v-model="selectedNode.style.backgroundColor" @change="onStyleChange" />
</div>
<div>
<label>边框色</label>
<input type="color" v-model="selectedNode.style.borderColor" @change="onStyleChange" />
</div>
<div>
<label>宽度</label>
<input type="range" min="80" max="300" v-model.number="selectedNode.style.width" @change="onStyleChange" />
<span>{{ selectedNode.style.width || 120 }}px</span>
</div>
</div>
</div>
<!-- 图标选择 -->
<div class="property-section">
<h4>图标</h4>
<div class="icon-grid">
<div
v-for="icon in availableIcons"
:key="icon"
class="icon-option"
:class="{ active: selectedNode.style.icon === icon }"
@click="selectIcon(icon)"
>
<i :class="`icon-${icon}`"></i>
</div>
</div>
</div>
<!-- 业务配置(根据节点类型动态显示) -->
<div class="property-section" v-if="selectedNode.type === 'decision'">
<h4>决策条件</h4>
<textarea
v-model="selectedNode.config.condition"
placeholder="例如: amount > 1000"
@change="onConfigChange"
></textarea>
</div>
<div class="property-section" v-if="selectedNode.type === 'process'">
<h4>处理动作</h4>
<select v-model="selectedNode.config.action" @change="onConfigChange">
<option value="approve">审批通过</option>
<option value="reject">审批拒绝</option>
<option value="forward">转交</option>
<option value="custom">自定义</option>
</select>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import type { FlowNode } from '@/types/flow';
const props = defineProps<{
selectedNode: FlowNode | null;
}>();
const emit = defineEmits<{
'update:style': [nodeId: string, style: Partial<FlowNode['style']>];
'update:config': [nodeId: string, config: Record<string, any>];
}>();
const availableIcons = ['play', 'gear', 'question', 'check', 'user', 'file', 'database', 'api'];
const selectIcon = (icon: string) => {
if (props.selectedNode) {
emit('update:style', props.selectedNode.id, { icon });
}
};
const onStyleChange = () => {
if (props.selectedNode) {
emit('update:style', props.selectedNode.id, { ...props.selectedNode.style });
}
};
const onConfigChange = () => {
if (props.selectedNode && props.selectedNode.config) {
emit('update:config', props.selectedNode.id, { ...props.selectedNode.config });
}
};
const onPropertyChange = () => {
// 标签变化可能也需要触发更新
console.log('节点标签已更新:', props.selectedNode?.label);
};
</script>
<style scoped>
.property-panel {
width: 280px;
padding: 16px;
background: #fafafa;
border-left: 1px solid #e8e8e8;
overflow-y: auto;
}
.property-section {
margin-bottom: 20px;
}
.property-section label {
display: block;
margin-bottom: 6px;
font-weight: 500;
color: #333;
}
.style-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.icon-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
}
.icon-option {
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
border: 2px solid #ddd;
border-radius: 6px;
cursor: pointer;
font-size: 18px;
}
.icon-option:hover {
border-color: #409EFF;
}
.icon-option.active {
border-color: #409EFF;
background-color: #e6f7ff;
}
</style>
这个属性面板实现了响应式绑定:当用户在面板中修改任何属性时,对应的节点会实时更新。结合 Vue 3 的响应式系统,我们可以轻松实现这种双向同步。
4.2 构建上下文菜单系统
右键菜单是专业编辑器的标配。我们需要一个全局的、可动态配置的上下文菜单。
<!-- ContextMenu.vue -->
<template>
<div
v-if="visible"
class="context-menu"
:style="{ left: `${position.x}px`, top: `${position.y}px` }"
@click.stop
>
<div class="menu-item" @click="onMenuItemClick('copy')">
<i class="icon-copy"></i> 复制
<span class="shortcut">Ctrl+C</span>
</div>
<div class="menu-item" @click="onMenuItemClick('paste')">
<i class="icon-paste"></i> 粘贴
<span class="shortcut">Ctrl+V</span>
</div>
<div class="menu-divider"></div>
<div class="menu-item" @click="onMenuItemClick('delete')">
<i class="icon-delete"></i> 删除
<span class="shortcut">Del</span>
</div>
<div class="menu-divider" v-if="contextType === 'node'"></div>
<div class="menu-item" @click="onMenuItemClick('changeColor')" v-if="contextType === 'node'">
<i class="icon-palette"></i> 更改颜色
</div>
<div class="menu-item" @click="onMenuItemClick('editLabel')" v-if="contextType === 'node'">
<i class="icon-edit"></i> 编辑标签
</div>
<div class="menu-item" @click="onMenuItemClick('addNodeAfter')" v-if="contextType === 'node'">
<i class="icon-add"></i> 后方添加节点
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
type MenuContext = 'canvas' | 'node' | 'connection';
type MenuAction = 'copy' | 'paste' | 'delete' | 'changeColor' | 'editLabel' | 'addNodeAfter';
const props = defineProps<{
contextType: MenuContext;
contextData?: any; // 附加数据,如节点ID、连接ID等
}>();
const emit = defineEmits<{
'menu-action': [action: MenuAction, data?: any];
}>();
const visible = ref(false);
const position = ref({ x: 0, y: 0 });
// 显示菜单
const show = (x: number, y: number) => {
position.value = { x, y };
visible.value = true;
};
// 隐藏菜单
const hide = () => {
visible.value = false;
};
const onMenuItemClick = (action: MenuAction) => {
emit('menu-action', action, props.contextData);
hide();
};
// 点击菜单外部时关闭
const handleClickOutside = (event: MouseEvent) => {
const menuEl = document.querySelector('.context-menu');
if (menuEl && !menuEl.contains(event.target as Node)) {
hide();
}
};
// 全局监听点击和右键事件
onMounted(() => {
document.addEventListener('click', handleClickOutside);
document.addEventListener('contextmenu', (e) => {
// 如果不是在菜单内右键,则隐藏菜单
const menuEl = document.querySelector('.context-menu');
if (menuEl && !menuEl.contains(e.target as Node)) {
hide();
}
});
});
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside);
});
defineExpose({
show,
hide
});
</script>
<style scoped>
.context-menu {
position: fixed;
background: white;
border: 1px solid #ddd;
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
min-width: 180px;
z-index: 1000;
padding: 6px 0;
}
.menu-item {
padding: 8px 16px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
}
.menu-item:hover {
background-color: #f5f5f5;
}
.menu-item i {
margin-right: 8px;
color: #666;
}
.shortcut {
color: #999;
font-size: 12px;
}
.menu-divider {
height: 1px;
background-color: #eee;
margin: 6px 0;
}
</style>
在主编辑器组件中,我们需要监听画布、节点、连线的右键点击事件,并显示对应的上下文菜单:
// 在 FlowEditor.vue 的 setup 中
const contextMenuRef = ref();
const contextMenuData = ref();
// 节点右键点击
const onNodeContextMenu = (node: FlowNode, event: MouseEvent) => {
event.preventDefault();
contextMenuData.value = { type: 'node', id: node.id };
contextMenuRef.value?.show(event.clientX, event.clientY);
};
// 连线右键点击(在jsPlumb监听中触发)
const showConnectionContextMenu = (connection: any, x: number, y: number) => {
contextMenuData.value = { type: 'connection', id: connection.id };
contextMenuRef.value?.show(x, y);
};
// 画布空白处右键点击
const onCanvasContextMenu = (event: MouseEvent) => {
event.preventDefault();
contextMenuData.value = { type: 'canvas', x: event.offsetX, y: event.offsetY };
contextMenuRef.value?.show(event.clientX, event.clientY);
};
// 处理菜单项点击
const onMenuAction = (action: string, data: any) => {
switch (action) {
case 'delete':
if (data.type === 'node') {
deleteNode(data.id);
} else if (data.type === 'connection') {
deleteConnection(data.id);
}
break;
case 'changeColor':
if (data.type === 'node') {
const color = `#${Math.floor(Math.random()*16777215).toString(16)}`;
updateNodeStyle(data.id, { backgroundColor: color });
}
break;
case 'addNodeAfter':
if (data.type === 'node') {
// 在选中节点下方添加新节点
addNodeAfter(data.id);
}
break;
// ... 其他动作处理
}
};
通过组合式API和组件化,我们构建了一个灵活、可扩展的上下文菜单系统,能够根据点击对象的不同(画布、节点、连线)显示不同的菜单项。
5. JSON 序列化与流程持久化
对于企业级应用,流程图的持久化存储和版本管理至关重要。我们需要将画布上的图形状态转换为可序列化的JSON数据,并能从JSON数据准确还原流程图。
5.1 设计健壮的导出结构
一个完整的流程图导出应该包含所有必要的信息,以便能够精确还原。我们在 utils/export.ts 中实现导出逻辑:
// utils/export.ts
import type { FlowData, FlowNode, FlowConnection } from '@/types/flow';
import { jsPlumb } from 'jsplumb';
/**
* 从当前画布状态导出完整的流程图数据
*/
export function exportFlowData(
nodes: FlowNode[],
connections: FlowConnection[],
jsPlumbInstance: any
): FlowData {
// 1. 序列化节点数据
const serializedNodes = nodes.map(node => ({
...node,
// 确保position是纯数据,没有响应式代理
position: { ...node.position }
}));
// 2. 序列化连接数据(从jsPlumb实例获取实时连接状态)
const allConnections = jsPlumbInstance.getAllConnections();
const serializedConnections: FlowConnection[] = allConnections.map((conn: any) => {
const sourceInfo = conn.endpoints[0];
const targetInfo = conn.endpoints[1];
return {
id: conn.id || `conn_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
sourceId: sourceInfo.element.id,
targetId: targetInfo.element.id,
sourceEndpoint: sourceInfo.anchor.type,
targetEndpoint: targetInfo.anchor.type,
label: conn.getOverlay('label')?.getLabel() || '',
style: {
stroke: conn.paintStyle.stroke,
strokeWidth: conn.paintStyle.strokeWidth,
dashstyle: conn.paintStyle.dashstyle
}
};
});
// 3. 获取当前视图状态(缩放、平移)
const viewport = {
zoom: jsPlumbInstance.getZoom() || 1,
pan: jsPlumbInstance.getPan() || { x: 0, y: 0 }
};
// 4. 添加元数据
const meta = {
exportTime: new Date().toISOString(),
version: '1.0',
tool: 'VueFlowEditor'
};
return {
meta,
nodes: serializedNodes,
connections: serializedConnections,
viewport
};
}
/**
* 将流程图数据导出为JSON字符串,支持美化格式
*/
export function exportToJSON(
flowData: FlowData,
options: { pretty: boolean } = { pretty: true }
): string {
const replacer = (key: string, value: any) => {
// 过滤掉undefined和函数
if (value === undefined || typeof value === 'function') {
return null;
}
return value;
};
if (options.pretty) {
return JSON.stringify(flowData, replacer, 2);
}
return JSON.stringify(flowData, replacer);
}
/**
* 将流程图数据导出为可下载的文件
*/
export function downloadFlowData(
flowData: FlowData,
filename: string = `flowchart_${new Date().getTime()}.json`
): void {
const jsonStr = exportToJSON(flowData);
const blob = new Blob([jsonStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
// 清理
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 100);
}
/**
* 生成流程图预览图(缩略图)
* 注意:这需要画布在可视区域内且已渲染完成
*/
export async function generateThumbnail(
container: HTMLElement,
options: { width: number; height: number } = { width: 400, height: 300 }
): Promise<string> {
return new Promise((resolve, reject) => {
// 使用html2canvas或dom-to-image等库生成图片
// 这里是一个简化示例
try {
// 临时克隆容器,避免影响原画布
const clone = container.cloneNode(true) as HTMLElement;
clone.style.width = `${options.width}px`;
clone.style.height = `${options.height}px`;
clone.style.position = 'fixed';
clone.style.left = '-9999px';
document.body.appendChild(clone);
// 实际项目中,这里应使用html2canvas
// const canvas = await html2canvas(clone, { ... });
// const dataUrl = canvas.toDataURL('image/png');
// 简化:返回一个占位符
const dataUrl = 'data:image/svg+xml;base64,...'; // 实际应为生成的图片数据
document.body.removeChild(clone);
resolve(dataUrl);
} catch (error) {
reject(error);
}
});
}
5.2 实现精确的导入与恢复
导入是导出的逆过程,但更加复杂,因为我们需要重新创建所有节点和连接,并恢复它们的交互状态。
// utils/import.ts
import type { FlowData, FlowNode, FlowConnection } from '@/types/flow';
import { jsPlumb } from 'jsplumb';
/**
* 验证导入的流程图数据是否有效
*/
export function validateFlowData(data: any): data is FlowData {
if (!data || typeof data !== 'object') {
throw new Error('无效的流程图数据:数据为空或不是对象');
}
if (!Array.isArray(data.nodes)) {
throw new Error('无效的流程图数据:nodes必须是数组');
}
if (!Array.isArray(data.connections)) {
throw new Error('无效的流程图数据:connections必须是数组');
}
// 验证每个节点的基本结构
data.nodes.forEach((node: any, index: number) => {
if (!node.id || typeof node.id !== 'string') {
throw new Error(`节点 ${index} 缺少有效的id`);
}
if (!node.position || typeof node.position.x !== 'number' || typeof node.position.y !== 'number') {
throw new Error(`节点 ${node.id} 缺少有效的位置信息`);
}
});
// 验证每个连接的基本结构
data.connections.forEach((conn: any, index: number) => {
if (!conn.sourceId || !conn.targetId) {
throw new Error(`连接 ${index} 缺少源节点或目标节点ID`);
}
});
return true;
}
/**
* 从JSON字符串导入流程图数据
*/
export function importFromJSON(jsonStr: string): FlowData {
try {
const data = JSON.parse(jsonStr);
if (validateFlowData(data)) {
return data;
}
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error('JSON解析失败:数据格式不正确');
}
throw error;
}
throw new Error('未知的导入错误');
}
/**
* 将流程图数据恢复到画布上
*/
export async function restoreFlowToCanvas(
flowData: FlowData,
jsPlumbInstance: any,
nodeFactory: (node: FlowNode) => HTMLElement
): Promise<void> {
// 1. 清空现有画布
jsPlumbInstance.reset();
// 2. 创建并添加节点到DOM
const nodeElements: Record<string, HTMLElement> = {};
flowData.nodes.forEach(node => {
const element = nodeFactory(node);
element.id = node.id;
element.style.left = `${node.position.x}px`;
element.style.top = `${node.position.y}px`;
element.style.backgroundColor = node.style.backgroundColor;
// 添加到画布容器
jsPlumbInstance.getContainer().appendChild(element);
nodeElements[node.id] = element;
// 使节点可拖拽
jsPlumbInstance.draggable(element, {
containment: 'parent',
drag: (params: any) => {
// 更新节点位置数据
console.log(`节点 ${node.id} 被拖拽到:`, params.pos);
}
});
});
// 3. 等待DOM更新完成
await new Promise(resolve => setTimeout(resolve, 0));
// 4. 恢复连接
flowData.connections.forEach(conn => {
const sourceEl = nodeElements[conn.sourceId];
const targetEl = nodeElements[conn.targetId];
if (!sourceEl || !targetEl) {
console.warn(`无法恢复连接 ${conn.sourceId} -> ${conn.targetId}:节点不存在`);
return;
}
try {
const connection = jsPlumbInstance.connect({
source: sourceEl,
target: targetEl,
anchors: [conn.sourceEndpoint || 'Right', conn.targetEndpoint || 'Left'],
paintStyle: conn.style,
overlays: conn.label ? [
['Label', { label: conn.label, location: 0.5, cssClass: 'connection-label' }]
] : []
});
// 恢复连接ID
if (conn.id) {
connection.id = conn.id;
}
} catch (error) {
console.error(`恢复连接失败 ${conn.sourceId} -> ${conn.targetId}:`, error);
}
});
// 5. 恢复视图状态
if (flowData.viewport) {
jsPlumbInstance.setZoom(flowData.viewport.zoom, false);
jsPlumbInstance.setPan(flowData.viewport.pan.x, flowData.viewport.pan.y);
}
// 6. 重新绘制所有连接
jsPlumbInstance.repaintEverything();
}
/**
* 从文件导入流程图数据
*/
export function importFromFile(file: File): Promise<FlowData> {
return new Promise((resolve, reject) => {
if (!file.type.includes('json')) {
reject(new Error('仅支持JSON格式文件'));
return;
}
const reader = new FileReader();
reader.onload = (event) => {
try {
const jsonStr = event.target?.result as string;
const flowData = importFromJSON(jsonStr);
resolve(flowData);
} catch (error) {
reject(error);
}
};
reader.onerror = () => {
reject(new Error('文件读取失败'));
};
reader.readAsText(file);
});
}
/**
* 生成流程图的唯一标识(用于版本管理)
*/
export function generateFlowHash(flowData: FlowData): string {
// 移除元数据和视图状态,只对核心数据进行哈希
const { meta, viewport, ...coreData } = flowData;
const jsonStr = JSON.stringify(coreData);
// 简单哈希函数(实际项目中应使用更可靠的哈希算法)
let hash = 0;
for (let i = 0; i < jsonStr.length; i++) {
const char = jsonStr.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // 转换为32位整数
}
return Math.abs(hash).toString(36);
}
5.3 实现自动保存与版本管理
对于复杂的流程图编辑,自动保存和版本回溯是必不可少的用户体验优化。
// utils/autoSave.ts
import { throttle } from 'lodash-es';
import type { FlowData } from '@/types/flow';
const STORAGE_KEY = 'flow_editor_autosave';
const MAX_HISTORY = 50; // 最多保存50个历史版本
export class AutoSaveManager {
private history: FlowData[] = [];
private currentIndex = -1;
constructor() {
this.loadHistory();
}
/**
* 保存当前状态到历史记录
*/
save(flowData: FlowData): void {
// 深拷贝数据,避免引用问题
const snapshot = JSON.parse(JSON.stringify(flowData));
// 如果当前不是最新状态,则丢弃后面的历史
if (this.currentIndex < this.history.length - 1) {
this.history = this.history.slice(0, this.currentIndex + 1);
}
// 添加到历史记录
this.history.push(snapshot);
// 限制历史记录数量
if (this.history.length > MAX_HISTORY) {
this.history.shift();
}
this.currentIndex = this.history.length - 1;
// 保存到本地存储
this.persistHistory();
}
/**
* 撤销到上一个状态
*/
undo(): FlowData | null {
if (this.currentIndex > 0) {
this.currentIndex--;
return this.history[this.currentIndex];
}
return null;
}
/**
* 重做到下一个状态
*/
redo(): FlowData | null {
if (this.currentIndex < this.history.length - 1) {
this.currentIndex++;
return this.history[this.currentIndex];
}
return null;
}
/**
* 获取当前状态
*/
getCurrent(): FlowData | null {
if (this.currentIndex >= 0 && this.currentIndex < this.history.length) {
return this.history[this.currentIndex];
}
return null;
}
/**
* 获取历史记录信息
*/
getHistoryInfo(): { count: number; current: number; canUndo: boolean; canRedo: boolean } {
return {
count: this.history.length,
current: this.currentIndex + 1,
canUndo: this.currentIndex > 0,
canRedo: this.currentIndex < this.history.length - 1
};
}
/**
* 清空历史记录
*/
clear(): void {
this.history = [];
this.currentIndex = -1;
localStorage.removeItem(STORAGE_KEY);
}
/**
* 从本地存储加载历史记录
*/
private loadHistory(): void {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
const data = JSON.parse(saved);
this.history = data.history || [];
this.currentIndex = data.currentIndex || -1;
}
} catch (error) {
console.warn('加载自动保存历史失败:', error);
this.history = [];
this.currentIndex = -1;
}
}
/**
* 持久化历史记录到本地存储
*/
private persistHistory(): void {
try {
const data = {
history: this.history,
currentIndex: this.currentIndex,
timestamp: new Date().toISOString()
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
} catch (error) {
console.warn('保存自动保存历史失败:', error);
}
}
}
/**
* 创建自动保存的节流函数
*/
export function createAutoSaveThrottle(
saveFn: (flowData: FlowData) => void,
interval: number = 2000 // 默认2秒保存一次
): (flowData: FlowData) => void {
return throttle(saveFn, interval, {
leading: false, // 不立即执行
trailing: true // 在节流结束后执行
});
}
在主编辑器组件中使用自动保存:
// 在 FlowEditor.vue 的 setup 中
import { AutoSaveManager, createAutoSaveThrottle } from '@/utils/autoSave';
// 初始化自动保存管理器
const autoSaveManager = new AutoSaveManager();
// 创建节流保存函数
const autoSave = createAutoSaveThrottle((flowData: FlowData) => {
autoSaveManager.save(flowData);
console.log('自动保存完成');
}, 3000); // 每3秒保存一次
// 监听流程图数据变化,触发自动保存
watch(() => [nodes.value, connections.value], () => {
const flowData = exportFlowData(nodes.value, connections.value, jsPlumbInstance);
autoSave(flowData);
}, { deep: true, immediate: false });
// 添加快捷键支持撤销/重做
useEventListener('keydown', (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey) {
if (event.key === 'z' && !event.shiftKey) {
// Ctrl+Z: 撤销
event.preventDefault();
const previousState = autoSaveManager.undo();
if (previousState) {
restoreFlowToCanvas(previousState, jsPlumbInstance, createNodeElement);
}
} else if (event.key === 'z' && event.shiftKey) {
// Ctrl+Shift+Z: 重做
event.preventDefault();
const nextState = autoSaveManager.redo();
if (nextState) {
restoreFlowToCanvas(nextState, jsPlumbInstance, createNodeElement);
}
} else if (event.key === 's') {
// Ctrl+S: 手动保存
event.preventDefault();
const flowData = exportFlowData(nodes.value, connections.value, jsPlumbInstance);
downloadFlowData(flowData, `flowchart_${new Date().getTime()}.json`);
}
}
});
6. 高级功能:画布操作与性能优化
一个完整的流程图编辑器还需要支持画布级别的操作,如缩放、平移、多选、框选等,同时要保证在大规模节点下的流畅性能。
6.1 实现画布缩放与平移
// composables/useCanvasControl.ts
import { ref } from 'vue';
import { useEventListener } from '@vueuse/core';
export function useCanvasControl(containerRef: Ref<HTMLElement | undefined>) {
const zoomLevel = ref(1);
const panOffset = ref({ x: 0, y: 0 });
const isPanning = ref(false);
const lastMousePos = ref({ x: 0, y: 0 });
// 缩放画布
const zoom = (delta: number, center?: { x: number; y: number }) => {
const minZoom = 0.1;
const maxZoom = 3;
const zoomFactor = 1.1;
let newZoom = zoomLevel.value;
if (delta > 0) {
newZoom *= zoomFactor;
} else {
newZoom /= zoomFactor;
}
// 限制缩放范围
newZoom = Math.max(minZoom, Math.min(maxZoom, newZoom));
// 计算缩放中心
const container = containerRef.value;
if (container && center) {
const rect = container.getBoundingClientRect();
const centerX = center.x - rect.left;
const centerY = center.y - rect.top;
// 调整平移偏移,使缩放围绕鼠标位置
const scaleChange = newZoom / zoomLevel.value;
panOffset.value.x = centerX - (centerX - panOffset.value.x) * scaleChange;
panOffset.value.y = centerY - (centerY - panOffset.value.y) * scaleChange;
}
zoomLevel.value = newZoom;
applyTransform();
};
// 平移画布
const startPan = (clientX: number, clientY: number) => {
isPanning.value = true;
lastMousePos.value = { x: clientX, y: clientY };
};
const doPan = (clientX: number, clientY: number) => {
if (!isPanning.value) return;
const deltaX = clientX - lastMousePos.value.x;
const deltaY = clientY - lastMousePos.value.y;
panOffset.value.x += deltaX;
panOffset.value.y += deltaY;
lastMousePos.value = { x: clientX, y: clientY };
applyTransform();
};
const stopPan = () => {
isPanning.value = false;
};
// 应用变换到画布
const applyTransform = () => {
const container = containerRef.value;
if (!container) return;
container.style.transform = `translate(${panOffset.value.x}px, ${panOffset.value.y}px) scale(${zoomLevel.value})`;
container.style.transformOrigin = '0 0';
};
// 重置视图
const resetView = () => {
zoomLevel.value = 1;
panOffset.value = { x: 0, y: 0 };
applyTransform();
};
// 适应视图(将所有节点显示在视口中)
const fitToView = (nodes: Array<{ position: { x: number; y: number } }>) => {
if (!containerRef.value || nodes.length === 0) return;
const containerRect = containerRef.value.getBoundingClientRect();
const containerWidth = containerRect.width;
const containerHeight = containerRect.height;
// 计算所有节点的边界框
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
nodes.forEach(node => {
minX = Math.min(minX, node.position.x);
minY = Math.min(minY, node.position.y);
maxX = Math.max(maxX, node.position.x + 120); // 假设节点宽度120px
maxY = Math.max(maxY, node.position.y + 60); // 假设节点高度60px
});
const contentWidth = maxX - minX;
const contentHeight = maxY - minY;
// 计算合适的缩放比例
const scaleX = containerWidth / (contentWidth + 100); // 留出边距
const scaleY = containerHeight / (contentHeight + 100);
const newZoom = Math.min(scaleX, scaleY, 1); // 不超过100%
// 计算平移偏移,使内容居中
const offsetX = (containerWidth - contentWidth * newZoom) / 2 - minX * newZoom;
const offsetY = (containerHeight - contentHeight * newZoom) / 2 - minY * newZoom;
zoomLevel.value = newZoom;
panOffset.value = { x: offsetX, y: offsetY };
applyTransform();
};
// 绑定鼠标滚轮缩放
useEventListener(containerRef, 'wheel', (event: WheelEvent) => {
event.preventDefault();
zoom(event.deltaY > 0 ? -1 : 1, { x: event.clientX, y: event.clientY });
}, { passive: false });
// 绑定鼠标拖拽平移
useEventListener(containerRef, 'mousedown', (event: MouseEvent) => {
if (event.button === 1 || (event.button === 0 && event.altKey)) { // 中键或Alt+左键
event.preventDefault();
startPan(event.clientX, event.clientY);
}
});
useEventListener(window, 'mousemove', (event: MouseEvent) => {
if (isPanning.value) {
event.preventDefault();
doPan(event.clientX, event.clientY);
}
});
useEventListener(window, 'mouseup', () => {
if (isPanning.value) {
stopPan();
}
});
return {
zoomLevel,
panOffset,
zoom,
resetView,
fitToView,
startPan,
doPan,
stopPan
};
}
6.2 实现框选与多选功能
// composables/useSelection.ts
import { ref, reactive } from 'vue';
import type { FlowNode, FlowConnection } from '@/types/flow';
export function useSelection() {
const selectedNodes = ref<Set<string>>(new Set());
const selectedConnections = ref<Set<string>>(new Set());
const selectionRect = reactive({
x1: 0,
y1: 0,
x2: 0,
y2: 0,
visible: false
});
// 选择单个节点
const selectNode = (nodeId: string, addToSelection: boolean = false) => {
if (!addToSelection) {
clearSelection();
}
selectedNodes.value.add(nodeId);
// 这里可以触发高亮样式更新
updateNodeSelectionStyle(nodeId, true);
};
// 选择单个连接
const selectConnection = (connId: string, addToSelection: boolean = false) => {
if (!addToSelection) {
clearSelection();
}
selectedConnections.value.add(connId);
// 这里可以触发高亮样式更新
updateConnectionSelectionStyle(connId, true);
};
// 框选
const startMarqueeSelection = (startX: number, startY: number) => {
selectionRect.x1 = startX;
selectionRect.y1 = startY;
selectionRect.x2 = startX;
selectionRect.y2 = startY;
selectionRect.visible = true;
};
const updateMarqueeSelection = (currentX: number, currentY: number) => {
selectionRect.x2 = currentX;
selectionRect.y2 = currentY;
};
const finishMarqueeSelection = (nodes: FlowNode[], containerRect: DOMRect) => {
if (!selectionRect.visible) return;
const left = Math.min(selectionRect.x1, selectionRect.x2);
const top = Math.min(selectionRect.y1, selectionRect.y2);
const right = Math.max(selectionRect.x1, selectionRect.x2);
const bottom = Math.max(selectionRect.y1, selectionRect.y2);
// 清除当前选择
clearSelection();
// 检查哪些节点在选框内
nodes.forEach(node => {
const nodeRect = {
left: node.position.x,
top: node.position.y,
right: node.position.x + (node.style.width || 120),
bottom: node.position.y + (node.style.height || 60)
};
// 简单的矩形碰撞检测
if (nodeRect.right > left && nodeRect.left < right &&
nodeRect.bottom > top && nodeRect.top < bottom) {
selectedNodes.value.add(node.id);
updateNodeSelectionStyle(node.id, true);
}
});
selectionRect.visible = false;
};
// 清除选择
const clearSelection = () => {
// 清除节点高亮
selectedNodes.value.forEach(nodeId => {
updateNodeSelectionStyle(nodeId, false);
});
// 清除连接高亮
selectedConnections.value.forEach(connId => {
updateConnectionSelectionStyle(connId, false);
});
selectedNodes.value.clear();
selectedConnections.value.clear();
};
// 批量操作选中的元素
const moveSelectedNodes = (deltaX: number, deltaY: number) => {
selectedNodes.value.forEach(nodeId => {
// 这里需要更新节点的位置数据
// 实际实现中,这会触发节点位置更新和jsPlumb重绘
console.log(`移动节点 ${nodeId}:`, deltaX, deltaY);
});
};
const deleteSelected = () => {
// 删除选中的节点
selectedNodes.value.forEach(nodeId => {
// 触发节点删除逻辑
console.log(`删除节点 ${nodeId}`);
});
// 删除选中的连接
selectedConnections.value.forEach(connId => {
// 触发连接删除逻辑
console.log(`删除连接 ${connId}`);
});
clearSelection();
};
// 更新节点选择样式(实际实现中需要操作DOM)
const updateNodeSelectionStyle = (nodeId: string, selected: boolean) => {
const nodeEl = document.getElementById(nodeId);
if (nodeEl) {
if (selected) {
nodeEl.classList.add('selected');
nodeEl.style.boxShadow = '0 0 0 2px #1890ff';
} else {
nodeEl.classList.remove('selected');
nodeEl.style.boxShadow = '';
}
}
};
// 更新连接选择样式
const updateConnectionSelectionStyle = (connId: string, selected: boolean) => {
// jsPlumb连接的选择样式需要通过API设置
console.log(`更新连接 ${connId} 选择状态:`, selected);
};
return {
selectedNodes,
selectedConnections,
selectionRect,
selectNode,
selectConnection,
startMarqueeSelection,
updateMarqueeSelection,
finishMarqueeSelection,
clearSelection,
moveSelectedNodes,
deleteSelected
};
}
6.3 性能优化:虚拟滚动与按需渲染
当流程图变得非常庞大时(数百甚至上千个节点),直接渲染所有节点会导致严重的性能问题。我们可以实现虚拟滚动和按需渲染来优化性能。
// composables/useVirtualRender.ts
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { throttle } from 'lodash-es';
import type { FlowNode } from '@/types/flow';
export function useVirtualRender(
containerRef: Ref<HTMLElement | undefined>,
allNodes: Ref<FlowNode[]>,
options: { viewportPadding: number } = { viewportPadding: 200 }
) {
const viewport = ref({ width: 0, height: 0, scrollX: 0, scrollY: 0 });
const visibleNodes = ref<FlowNode[]>([]);
// 计算可见区域
const visibleArea = computed(() => {
const padding = options.viewportPadding;
return {
left: viewport.value.scrollX - padding,
top: viewport.value.scrollY - padding,
right: viewport.value.scrollX + viewport.value.width + padding,
bottom: viewport.value.scrollY + viewport.value.height + padding
};
});
// 过滤出在可见区域内的节点
const updateVisibleNodes = throttle(() => {
if (!allNodes.value.length) {
visibleNodes.value = [];
return;
}
const area = visibleArea.value;
visibleNodes.value = allNodes.value.filter(node => {
const nodeRight = node.position.x + (node.style.width || 120);
const nodeBottom = node.position.y + (node.style.height || 60);
return nodeRight > area.left &&
node.position.x < area.right &&
nodeBottom > area.top &&
node.position.y < area.bottom;
});
console.log(`渲染 ${visibleNodes.value.length}/${allNodes.value.length} 个节点`);
}, 100);
// 监听容器滚动和大小变化
const updateViewport = () => {
const container = containerRef.value;
if (!container) return;
viewport.value = {
width: container.clientWidth,
height: container.clientHeight,
scrollX: container.scrollLeft,
scrollY: container.scrollTop
};
updateVisibleNodes();
};
// 初始化
onMounted(() => {
const container = containerRef.value;
if (!container) return;
// 初始更新
updateViewport();
// 监听滚动
container.addEventListener('scroll', updateViewport);
// 监听大小变化
const resizeObserver = new ResizeObserver(updateViewport);
resizeObserver.observe(container);
// 清理函数
onUnmounted(() => {
container.removeEventListener('scroll', updateViewport);
resizeObserver.disconnect();
});
});
// 当节点数据变化时更新
watch(allNodes, updateVisibleNodes, { deep: true });
return {
visibleNodes,
viewport,
updateViewport
};
}
在主编辑器组件中使用虚拟渲染:
<!-- FlowEditor.vue 部分代码 -->
<template>
<div class="flow-editor" ref="containerRef" @scroll="onScroll">
<!-- 画布容器,应用缩放和平移 -->
<div
class="flow-canvas"
:style="canvasStyle"
@mousedown="onCanvasMouseDown"
>
<!-- 只渲染可见节点 -->
<FlowNode
v-for="node in visibleNodes"
:key="node.id"
:node="node"
@node-click="onNodeClick"
@node-contextmenu="onNodeContextMenu"
/>
<!-- 选择框 -->
<div
v-if="selectionRect.visible"
class="selection-rect"
:style="selectionRectStyle"
></div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useVirtualRender } from '@/composables/useVirtualRender';
const containerRef = ref<HTMLElement>();
const { visibleNodes, updateViewport } = useVirtualRender(containerRef, nodes);
// 画布样式(包含缩放和平移)
const canvasStyle = computed(() => ({
transform: `translate(${panOffset.x}px, ${panOffset.y}px) scale(${zoomLevel})`,
transformOrigin: '0 0',
width: `${canvasWidth}px`,
height: `${canvasHeight}px`
}));
// 选择框样式
const selectionRectStyle = computed(() => {
const left = Math.min(selectionRect.x1, selectionRect.x2);
const top = Math.min(selectionRect.y1, selectionRect.y2);
const width = Math.abs(selectionRect.x2 - selectionRect.x1);
const height = Math.abs(selectionRect.y2 - selectionRect.y1);
return {
left: `${left}px`,
top: `${top}px`,
width: `${width}px`,
height: `${height}px`
};
});
const onScroll = () => {
updateViewport();
};
const onCanvasMouseDown = (event: MouseEvent) => {
// 如果按住Shift键,开始框选
if (event.shiftKey && event.button === 0) {
const rect = containerRef.value?.getBoundingClientRect();
if (rect) {
const startX = event.clientX - rect.left;
const startY = event.clientY - rect.top;
startMarqueeSelection(startX, startY);
}
}
};
</script>
<style scoped>
.flow-editor {
width: 100%;
height: 100%;
overflow: auto;
position: relative;
}
.flow-canvas {
position: relative;
min-width: 2000px;
min-height: 2000px;
background: #f8f9fa;
background-image:
linear-gradient(rgba(0, 0, 0, 0.05) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 0, 0, 0.05) 1px, transparent 1px);
background-size: 20px 20px;
}
.selection-rect {
position: absolute;
border: 2px dashed #1890ff;
background: rgba(24, 144, 255, 0.1);
pointer-events: none;
z-index: 1000;
}
</style>
7. 实战:构建一个完整的审批流程设计器
现在,让我们将前面所有的模块组合起来,构建一个完整的审批流程设计器。这个设计器将包含工具栏、节点面板、属性编辑器、画布和状态栏。
7.1 主编辑器组件集成
<!-- FlowEditor.vue 完整示例 -->
<template>
<div class="flow-editor-container">
<!-- 顶部工具栏 -->
<Toolbar
:zoom-level="zoomLevel"
@zoom-in="zoom(0.1)"
@zoom-out="zoom(-0.1)"
@zoom-reset="resetView"
@zoom-fit="fitToView"
@undo="handleUndo"
@redo="handleRedo"
@save="handleSave"
@load="handleLoad"
@export-image="exportAsImage"
/>
<div class="editor-main">
<!-- 左侧节点面板 -->
<Sidebar
:node-templates="nodeTemplates"
@drag-start="onNodeDragStart"
/>
<!-- 中间画布区域 -->
<div class="canvas-container" ref="canvasContainerRef">
<div
class="flow-editor"
ref="editorRef"
@contextmenu="onCanvasContextMenu"
@drop="onCanvasDrop"
@dragover.prevent
>
<!-- 节点列表(使用虚拟渲染) -->
<FlowNode
v-for="node in visibleNodes"
:key="node.id"
:node="node"
@node-click="onNodeClick"
@node-contextmenu="onNodeContextMenu"
@update:position="onNodePositionUpdate"
/>
</div>
<!-- 选择框 -->
<div
v-if="selectionRect.visible"
class="selection-re
1956



被折叠的 条评论
为什么被折叠?



