vue 实现动态连线
Vue 实现动态连线的方法
动态连线通常用于可视化工具、流程图或关系图中,Vue 结合 SVG 或 Canvas 可以高效实现这一功能。
使用 SVG 实现动态连线
SVG 的 <line> 或 <path> 元素适合绘制动态连线,结合 Vue 的响应式数据绑定实现动态更新。
<template>
<svg width="500" height="500">
<line
:x1="start.x"
:y1="start.y"
:x2="end.x"
:y2="end.y"
stroke="black"
stroke-width="2"
/>
</svg>
</template>
<script>
export default {
data() {
return {
start: { x: 50, y: 50 },
end: { x: 200, y: 200 }
};
}
};
</script>
使用第三方库(如 jsPlumb)
jsPlumb 是一个强大的连线库,支持拖拽、动态连接和样式自定义。
<template>
<div>
<div id="source" class="node">Source</div>
<div id="target" class="node">Target</div>
</div>
</template>
<script>
import { jsPlumb } from 'jsplumb';
export default {
mounted() {
jsPlumb.ready(() => {
jsPlumb.connect({
source: "source",
target: "target",
anchors: ["Right", "Left"],
connector: ["Straight"],
paintStyle: { stroke: "#456", strokeWidth: 3 }
});
});
}
};
</script>
<style>
.node {
width: 100px;
height: 50px;
border: 1px solid #ccc;
position: absolute;
}
#source { left: 50px; top: 50px; }
#target { left: 300px; top: 150px; }
</style>
使用 Canvas 动态绘制连线
Canvas 适合高性能动态渲染,通过 Vue 监听数据变化触发重绘。
<template>
<canvas ref="canvas" width="500" height="500"></canvas>
</template>
<script>
export default {
data() {
return {
start: { x: 50, y: 50 },
end: { x: 300, y: 300 }
};
},
mounted() {
this.drawLine();
},
methods: {
drawLine() {
const ctx = this.$refs.canvas.getContext('2d');
ctx.clearRect(0, 0, 500, 500);
ctx.beginPath();
ctx.moveTo(this.start.x, this.start.y);
ctx.lineTo(this.end.x, this.end.y);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.stroke();
}
},
watch: {
start: { handler: 'drawLine', deep: true },
end: { handler: 'drawLine', deep: true }
}
};
</script>
动态响应鼠标事件
通过 Vue 绑定鼠标事件实现交互式连线。
<template>
<svg width="500" height="500" @mousemove="updateEnd" @click="setStart">
<line
:x1="start.x"
:y1="start.y"
:x2="end.x"
:y2="end.y"
stroke="green"
stroke-width="3"
/>
</svg>
</template>
<script>
export default {
data() {
return {
start: { x: 100, y: 100 },
end: { x: 100, y: 100 }
};
},
methods: {
setStart(event) {
this.start = { x: event.offsetX, y: event.offsetY };
},
updateEnd(event) {
this.end = { x: event.offsetX, y: event.offsetY };
}
}
};
</script>
关键注意事项
- 性能优化:频繁更新的动态连线建议使用 Canvas 或第三方库(如 jsPlumb),避免 SVG 的 DOM 操作开销。
- 响应式监听:通过 Vue 的
watch或计算属性实时更新连线坐标。 - 交互设计:结合拖拽库(如 draggable)实现节点移动时连线自动更新。







