Vue 3 + jsPlumb实战:5步搞定可交互流程图(附JSON导入导出技巧)

vue3.x 使用jsplumb进行拖拽连线 如果想在vue2里面使用jsplumb 可以查看 文章,下面讲解如何在vue3.x 里面使用jsplumb进行拖拽连线 阅读详情

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
Vue 3 + jsPlumb 实战:如何用JSON数据动态生成可编辑流程图(附完整代码) 本文详细介绍了如何使用Vue 3和jsPlumb开发JSON数据驱动的动态流程图编辑器。通过响应式数据绑定和可视化编程技术,实现流程图的动态生成、编辑与样式配置,并提供完整代码示例和性能优化建议,助力开发者快速构建高效的可视化工作流工具。 阅读详情

相关推荐

前端拓扑图编辑器vue3+jsplumb

## 项目概述 - **项目名称**: jsPlumb 拓扑图编辑器 - **项目类型**: 单页面Web应用 - **核心功能**: 可视化拓扑图编辑,支持节点的增删和连线管理 - **目标用户**: 需要创建网络拓扑图、系统架构图的用户 ### 核心功能 1. **新增节点** - 点击工具栏"新增节点"按钮 - 在画布中心添加新节点 - 节点自动编号 (Node 1, Node 2, ...) - 节点可拖拽到任意位置 2. **删除节点** - 选中节点,点击工具栏删除按钮 - 或右键节点选择"删除" - 删除节点时自动删除相关连线 3. **新增连线** - 从一个节点的锚点拖拽到另一个节点的锚点 - 自动创建连接线 - 支持双向连接 4. **删除连线** - 选中连线(点击线条) - 按Delete键或点击删除按钮 ### 用户交互 - **拖拽节点**: 点击并拖动节点 - **创建连接**: 从锚点拖拽到另一个锚点 - **选中**: 点击节点或连线选中 - **取消选中**: 点击画布空白区域 - **删除**: 选中后按Delete键

vue3使用jsPlumb,给元素连接线条

/nextTick在页面重新渲染完成后执行,解决想要“增加数据dataList”功能中出现的“Cannot establish connection - source does not exist”问题。// 添加样式#007fff藏青色,#1E90FF宝石蓝,#4169E1偏暗的青蓝色,引入:import { jsPlumb } from 'jsplumb';//定义线的样式 defaultConfig1。// 添加 overlay,如箭头。//relation1,2为节点映射。

m0_63498559的博客 1956

基于线性光耦HCNR200的高压直流采样电路设计与精度优化

本文详细介绍了基于线性光耦HCNR200的高压直流采样电路设计与精度优化方法。针对直流高电压测量中的安全与干扰问题,提出采用HCNR200光耦隔离方案,实现高精度线性传输。文章深入解析电路设计关键细节,包括电阻网络、运放选型、滤波电容配置等,并提供精度优化实战技巧与常见问题排查指南,助力新能源电动汽车和高压储能系统的高压直流采样应用。

weixin_42713608的博客 582

Vue 3 + jsPlumb 打造可视化流程图组件(支持图标与颜色配置)

Vue 3 + jsPlumb 打造可视化流程图组件(支持图标与颜色配置)

idree的博客 2856

ModusToolbox 实战避坑指南|从环境配置到项目构建

本文是一份详尽的ModusToolbox实战避坑指南,手把手教你从环境配置到项目构建。重点解决了Windows系统下的安装、关键环境变量CY_TOOLS_PATHS的设置、PowerShell执行策略调整以及利用URL Modifier工具优化GitHub资源下载等核心难题,旨在帮助开发者,特别是英飞凌(Infineon)芯片用户,顺利搭建开发环境并成功运行第一个Hello World程序。

t1u2v的博客 592

避开这些坑!用Python ReportLab生成PDF时字体处理与中文排版的5个关键技巧

本文针对Python ReportLab库在PDF自动化生成中常见的中文排版难题,提供了五个关键技巧。内容涵盖字体注册的稳健策略、段落样式的精细控制、表格内中文的换行对齐、页面布局管理以及性能优化,旨在帮助开发者彻底解决中文乱码、排版错位等问题,生成专业美观的PDF文档。

weixin_29250403的博客 625

开发(1):Vue3中使用jsPlumb

本文介绍了使用jsPlumb实现拓扑流程图的方法,主要包括安装和核心实现代码。

欢迎指出不足之处 544

43_AI短片实战第十六弹:AIGC补充特写镜头——首尾帧衔接与多图抽卡技巧

本文介绍了使用Templa AI平台生成"怪兽爬车"特写镜头并衔接"甩尾摔下"动作的完整流程。首先通过AI生成4张怪兽趴在车顶的特写画面,重点选择展示怪兽与车顶关系的构图(16:9比例)。然后将选定的首帧图与已有尾帧图输入AI,生成7秒左右的过渡视频,实现从"稳定趴车"到"开始摔落"的自然衔接。整个过程展示了单图抽卡策略、首尾帧选择标准,以及如何利用AI生成时间进行其他剪辑任务的并行处理方法。最终产出包括特写首帧图、过渡视频文件和更新后的剪辑项目。

Open 82

Vue 3 + jsPlumb 实现动态可配置流程图编辑器(JSON驱动与自动布局)

本文详细介绍了如何利用Vue 3和jsPlumb构建一个动态可配置的流程图编辑器。该方案的核心在于通过JSON数据驱动视图渲染,实现流程图与数据的双向绑定,并集成Dagre.js实现智能自动布局,最终封装为高性能、可复用的Vue组件,适用于低代码平台和流程编排等场景。

weixin_29008055的博客 310

Python从0到100(十九):Python标准库初探

哈希函数又称哈希算法或散列函数,是一种为已有的数据创建“数字指纹”(哈希摘要)的方法。哈希函数把数据压缩成摘要,对于相同的输入,哈希函数可以生成相同的摘要(数字指纹),需要注意的是这个过程并不可逆(不能通过摘要计算出输入的内容)。举一个简单的例子,用户注册时我们希望在数据库中保存用户的密码,很显然我们不能将用户密码直接保存在数据库中,这样可能会导致用户隐私的泄露,所以在数据库中保存用户密码时,通常都会将密码的“指纹”保存起来,用户登录时通过哈希函数计算密码的“指纹”再进行匹配来判断用户登录是否成功。

拥有百余位万粉技术博主、200余位可合作代发博主,私域技术社群规模达千人,商务合作私信 5006

Python爬虫实战:构建药监局药品批准信息本地查询系统

在医药信息化时代,药品批准信息的快速查询对于医药从业者、研究人员和普通消费者都具有重要意义。国家药品监督管理局(NMPA)提供了官方的药品查询系统,但有时我们需要建立本地数据库以便批量分析或离线查询。本文将详细介绍如何使用Python爬虫技术,结合最新的异步爬虫框架和技术栈,构建一个完整的药监局药品信息本地查询系统。本系统将实现以下功能:自动化爬取药监局官网的药品批准信息数据清洗和结构化存储建立本地查询接口数据定期更新机制pythonimport os"""药品类型枚举"""

2201_76125261的博客 731

三步搞定数据血缘可视化:jsplumb-dataLineage-vue终极指南

你是否曾经面对复杂的数据处理流程感到迷茫?数据从哪里来,经过哪些转换,最终流向何处?这些问题在数据治理和ETL开发中尤为关键。今天,我将为你揭秘一个免费开源的神器——jsplumb-dataLineage-vue,让你轻松构建专业级的数据血缘关系图! ## 数据血缘可视化的痛点与解决方案 在数据驱动的时代,理解数据流动路径至关重要。然而,传统的手动绘制流程图方式存在诸多问题: - **维护困

gitblog_00414的博客 1004

字节最新开源模型 DA3(Depth Anything 3)使用教程(一)从任意视角恢复视觉空间

本文介绍DepthAnything3(DA3)模型,一种能够从任意视觉输入中预测几何结构的创新解决方案。DA3采用Transformer骨干网络,通过统一的深度光线表示简化学习过程,支持单目/多视角深度估计、姿态估计和3D高斯预测等多项任务。模型系列包含基础版、度量级和单目专用版本,其中嵌套版本DA3NESTED-GIANT-LARGE表现最佳。代码库提供交互界面、CLI工具和多格式导出功能,支持模块化扩展。实验表明DA3在各项任务上超越现有模型,所有训练数据均来自公开学术数据集。

2506_90492529的博客 2550

jsplumb-dataLineage-vue:数据血缘可视化深度解析与实战指南

jsplumb-dataLineage-vue是一个基于Vue.js和jsPlumb库构建的专业级数据血缘前端可视化工具,专门用于展示数据流动路径和依赖关系。该项目支持Vue2和Vue3双版本,采用模块化架构设计,为数据治理、ETL开发和数据分析场景提供直观的数据流转图谱展示能力。 ## 技术架构设计思路与核心组件 ### 现代化技术栈构建 项目采用当前主流的前端技术栈,通过package.

gitblog_00240的博客 1063

【100%通过率】2023华为od机试C卷【围棋的气】Python 实现

围棋棋盘由纵横各19条线垂直相交组成,棋盘上一共19 x 19 = 361 个交点,对奔双方一方执白棋,一方执黑棋,落子时只能将棋子置于交点上。 “气”是围棋中很重要的一个概念,某个棋子有几口气,是指其上下左右方向四个相邻的交叉点中,有几个交叉点没有棋子,由此可知:

MISAYAONE的博客 1859

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Relay 上传映射 UploadableMap 类型解析:从定义到网络层传输的完整实战

本文围绕 Relay 14 官方文档中 `UploadableMap` 类型的定义,结合当前仓库中 `relay-runtime` 的类型声明、`commitMutation` 实现、`useMutation` Hook 以及网络层源码,系统讲解该类型在文件上传场景中的角色定位、在 `MutationConfig` 等 API 中的使用方式,以及网络层接收与传输的边界约束。读完本文,你将理解 `U

gitblog_01141的博客 980

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Vue流程图构建终极指南:5分钟快速上手jsplumb工作流

想要在Vue项目中快速构建专业的流程图编辑器吗?vue-draggable-workflow项目基于sortablejs和jsplumb.js,为你提供完整的可视化工作流解决方案。这款开源工具支持节点拖拽、条件分支、多路径逻辑,让你在5分钟内就能创建复杂的工作流界面!🚀 ## ✨ 核心功能亮点 ### 可视化拖拽编辑 - **智能节点拖拽**:从工具栏轻松拖拽节点到画布 - **实时连线逻辑

gitblog_00892的博客 798

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

如何快速构建专业级数据血缘图:jsplumb-dataLineage-vue 终极指南 [特殊字符]

还在为复杂的数据流转关系而头疼吗?数据血缘可视化是数据治理和ETL开发中的关键环节,但传统的手工绘图方式既耗时又容易出错。jsplumb-dataLineage-vue项目为你提供了一个简单高效的解决方案——这是一个基于Vue.js和jsPlumb库的数据血缘前端展示工具,能够让你在几分钟内创建出专业级的数据流动关系图。无论你是数据工程师、数据分析师还是数据治理专家,这个开源工具都能大幅提升你的工

gitblog_00359的博客 968

终极数据血缘可视化神器:5分钟快速上手jsplumb-dataLineage-vue

还在为复杂的数据流转关系头疼吗?jsplumb-dataLineage-vue项目为你提供了一套完整、简单、免费的解决方案!这个基于Vue.js和jsPlumb库的数据血缘前端展示工具,能够帮助你快速构建直观的数据流动关系图,无论是数据治理专家、ETL开发者还是数据分析师,都能在5分钟内上手使用。数据血缘可视化从未如此简单高效! ## 🎯 为什么你需要数据血缘可视化工具? 在数据驱动的时代,

gitblog_01140的博客 412

构建高性能数据血缘可视化系统:基于Vue.js与jsPlumb的云原生架构实践

在数据治理和ETL开发领域,数据血缘可视化已成为企业数据架构的核心组件。jsplumb-dataLineage-vue项目基于Vue.js和jsPlumb库,通过声明式配置和事件驱动架构,为技术决策者提供了一套高性能、可扩展的数据血缘前端解决方案。该项目通过智能节点渲染引擎和实时交互机制,实现了复杂数据关系的可视化表达,解决了传统数据血缘分析中可视化效果差、交互体验不足的技术痛点。 ## 技术架

gitblog_00529的博客 481

easy-flow:基于VUE+JsPlumb打造终极流程设计器,拖拽式可视化编程新体验

easy-flow是一款基于VUE+ElementUI+JsPlumb的流程设计器,通过vuedraggable插件实现节点拖拽,帮助开发者快速构建可视化工作流。无论是新手还是专业开发者,都能通过简单的拖拽操作创建复杂的流程图,极大提升工作效率。 ## 为什么选择easy-flow?5大核心优势解析 ### 1. 拖拽式操作,零基础也能快速上手 🚀 无需复杂代码知识,只需从左侧菜单拖拽子节点

gitblog_00689的博客 1064

终极数据血缘可视化工具:jsplumb-dataLineage-vue 完全指南

还在为复杂的数据流向而头疼吗?jsplumb-dataLineage-vue 为你带来革命性的数据血缘可视化解决方案!这个基于 Vue 和 jsPlumb 的开源项目,能够将抽象的数据关系转化为直观的图表,让数据流转一目了然。 ## 🚀 5分钟快速上手 想要立即体验数据血缘的魅力?只需几个简单步骤: 1. **克隆项目到本地**: ```bash git clone https://git

gitblog_00362的博客 381

jsPlumb实战:从零搭建可视化审批系统

审批系统需要支持用户通过拖拽方式创建审批流程,包括开始节点、审批节点和结束节点。每个审批节点需要配置审批人信息,节点之间通过连线建立关系,并且支持条件分支(通过/驳回)。通过监听jsPlumb的连接事件,确保流程图的合法性(如不能出现未连接的节点)。我们定义了三种基础节点类型:开始节点、审批节点和结束节点。jsPlumb的官方文档主要是英文的,我们在开发过程中整理了一套中文文档,方便团队其他成员使用。采用Pinia管理整个流程图的状态,包括节点列表、连线关系以及当前选中的元素。为我们提供了很大帮助。

AgatePanther34的博客 279

【已开源】基于Vue2和jsPlumb.js的模仿sqlFlow数据血缘图的前端页面【源代码已更新】

基于Vue和jsplumb的模仿sqlFLow数据血缘图的前端

mizuhokaga的博客 1万+

如何用Vue-draggable-workflow轻松创建交互式流程图:零基础入门指南

Vue-draggable-workflow是一款基于Vue.js和jsPlumb开发的开源流程图构建工具,让用户通过简单拖拽即可创建专业的工作流程图。无论是项目管理、业务流程设计还是教学演示,这款工具都能帮助你快速将复杂流程可视化,即使没有编程经验也能轻松上手。 ## ???? 核心功能:让流程图设计像搭积木一样简单 ### 拖拽式节点操作 Vue-draggable-workflow最直观的特...

gitblog_00138的博客 793
上一篇: 解决coc.nvim中clangd未安装问题:CocCommand clangd.install实战指南
下一篇: 使用Advanced Installer为Flutter Windows应用打造专业安装包(含静默安装、注册表清理与自动更新)
普通网友
博客等级 码龄27年 205粉丝 1502原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值