当前位置:首页 > VUE

vue实现组件连线动画

2026-02-23 17:27:07VUE

Vue 实现组件连线动画

使用 SVG 和动态路径

在 Vue 中可以通过 SVG 的 <path> 元素结合动态属性实现连线动画。定义两个组件的坐标点,通过计算路径的 d 属性生成贝塞尔曲线或直线路径。

<template>
  <svg width="500" height="300">
    <path 
      :d="`M${startX},${startY} C${controlX1},${controlY1} ${controlX2},${controlY2} ${endX},${endY}`" 
      stroke="#3498db" 
      stroke-width="2" 
      fill="none"
      ref="linePath"
    />
  </svg>
</template>

<script>
export default {
  data() {
    return {
      startX: 50,  // 起点组件X坐标
      startY: 100,
      endX: 400,   // 终点组件X坐标
      endY: 200,
      controlX1: 150,
      controlY1: 50,
      controlX2: 300,
      controlY2: 250
    };
  }
};
</script>

添加动画效果

通过 CSS 或 GSAP 库实现路径绘制动画效果。使用 stroke-dasharraystroke-dashoffset 属性模拟绘制过程。

vue实现组件连线动画

<style scoped>
path {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: draw 2s forwards;
}

@keyframes draw {
  to {
    stroke-dashoffset: 0;
  }
}
</style>

动态响应组件位置变化

结合 Vue 的 ref 和生命周期钩子监听组件位置变化,使用 getBoundingClientRect() 获取动态坐标。

vue实现组件连线动画

export default {
  mounted() {
    window.addEventListener('resize', this.updateLinePath);
    this.updateLinePath();
  },
  methods: {
    updateLinePath() {
      const startEl = this.$refs.startComponent.$el;
      const endEl = this.$refs.endComponent.$el;

      const startRect = startEl.getBoundingClientRect();
      const endRect = endEl.getBoundingClientRect();

      this.startX = startRect.left + startRect.width/2;
      this.startY = startRect.top + startRect.height/2;
      this.endX = endRect.left + endRect.width/2;
      this.endY = endRect.top + endRect.height/2;
    }
  }
}

使用第三方库(可选)

对于复杂场景,可以使用专门处理连线的库如:

  • jsPlumb:提供拖拽连线、锚点配置等功能
  • LeaderLine:轻量级的连线库,支持多种连线样式
  • Rete.js:适用于可视化编程的连线方案

示例:jsPlumb 集成

安装后通过 Vue 指令或组件形式集成:

import { jsPlumb } from 'jsplumb';

export default {
  mounted() {
    jsPlumb.ready(() => {
      jsPlumb.connect({
        source: "component1",
        target: "component2",
        anchors: ["Right", "Left"],
        connector: ["Flowchart"]
      });
    });
  }
}

标签: 组件动画
分享给朋友:

相关文章

vue实现折叠组件

vue实现折叠组件

实现折叠组件的基本思路 在Vue中实现折叠组件通常需要利用动态绑定和条件渲染。核心是通过控制一个布尔值状态来决定内容是否显示,并添加过渡动画提升用户体验。 基础实现方法 使用v-show或v-if控…

vue动态组件实现

vue动态组件实现

动态组件的基本用法 在Vue中,动态组件通过<component>标签和is属性实现。is属性可以绑定组件名称或组件选项对象,实现动态切换。 <template> <…

如何缓存react组件

如何缓存react组件

缓存React组件的方法 React.memo 使用React.memo对函数组件进行浅比较缓存,避免不必要的重新渲染。适用于props不变的场景。 const MemoizedComponen…

vue实现分页组件

vue实现分页组件

Vue 分页组件实现 基础分页组件结构 创建一个名为 Pagination.vue 的文件,包含以下基础模板和逻辑: <template> <div class="pa…

vue 实现树组件

vue 实现树组件

Vue 树形组件实现 基础树形结构实现 使用递归组件实现树形结构,核心是通过组件自身调用自身渲染嵌套数据。 <template> <ul> <li v-fo…

vue组件实现注册

vue组件实现注册

Vue 组件注册的两种方式 全局注册 通过 Vue.component() 方法注册,注册后可在任意 Vue 实例中使用。通常在项目的入口文件(如 main.js)中操作: import V…