vue实现轨道功能
Vue 实现轨道功能的方法
轨道功能通常指在界面中实现元素沿特定路径移动的效果,例如进度条、时间轴或动画轨迹。以下是几种常见的实现方式:
使用 CSS 动画与 Vue 结合
通过 Vue 动态绑定样式或类名,结合 CSS @keyframes 或 transition 实现轨道动画。
<template>
<div class="track">
<div class="slider" :style="{ left: position + '%' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
position: 0
};
},
mounted() {
setInterval(() => {
this.position = (this.position + 1) % 100;
}, 50);
}
};
</script>
<style>
.track {
width: 100%;
height: 10px;
background: #eee;
position: relative;
}
.slider {
width: 20px;
height: 20px;
background: #42b983;
border-radius: 50%;
position: absolute;
top: -5px;
transition: left 0.1s linear;
}
</style>
使用 SVG 路径动画
通过 SVG 的 <path> 和 <animateMotion> 实现复杂轨迹运动。
<template>
<svg width="200" height="200">
<path
id="track"
d="M10,100 Q50,10 100,100 T190,100"
fill="none"
stroke="#ddd"
/>
<circle r="8" fill="#42b983">
<animateMotion
dur="3s"
repeatCount="indefinite"
path="M10,100 Q50,10 100,100 T190,100"
/>
</circle>
</svg>
</template>
基于第三方库(如 GSAP)
使用 GSAP 的 MotionPathPlugin 实现高级轨道动画。
<template>
<div ref="target" class="target"></div>
</template>
<script>
import { gsap } from "gsap";
import { MotionPathPlugin } from "gsap/MotionPathPlugin";
gsap.registerPlugin(MotionPathPlugin);
export default {
mounted() {
gsap.to(this.$refs.target, {
duration: 5,
repeat: -1,
motionPath: {
path: [
{ x: 0, y: 0 },
{ x: 100, y: -50 },
{ x: 200, y: 0 }
],
curviness: 1.5
}
});
}
};
</script>
<style>
.target {
width: 20px;
height: 20px;
background: #42b983;
border-radius: 50%;
}
</style>
动态数据驱动的轨道
结合 Vue 的响应式数据,实现轨道进度与数据绑定。
<template>
<div class="progress-track">
<div
class="progress-bar"
:style="{ width: progress + '%' }"
></div>
</div>
<button @click="progress += 10">增加进度</button>
</template>
<script>
export default {
data() {
return {
progress: 0
};
}
};
</script>
<style>
.progress-track {
width: 100%;
height: 8px;
background: #eee;
margin: 20px 0;
}
.progress-bar {
height: 100%;
background: #42b983;
transition: width 0.3s;
}
</style>
关键点说明
- CSS 动画:适合简单直线或固定路径,性能较好。
- SVG 路径:支持复杂曲线轨迹,但需熟悉 SVG 语法。
- GSAP 库:提供更灵活的动画控制,适合复杂交互场景。
- 数据绑定:通过 Vue 响应式数据实现动态更新,适合进度展示类需求。
根据具体需求选择合适的方法,复杂场景可组合使用多种技术。






