vue实现组件连线动画
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-dasharray 和 stroke-dashoffset 属性模拟绘制过程。
<style scoped>
path {
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
animation: draw 2s forwards;
}
@keyframes draw {
to {
stroke-dashoffset: 0;
}
}
</style>
动态响应组件位置变化
结合 Vue 的 ref 和生命周期钩子监听组件位置变化,使用 getBoundingClientRect() 获取动态坐标。
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"]
});
});
}
}





