vue实现子弹循环
Vue 实现子弹循环动画
在 Vue 中实现子弹循环动画可以通过 CSS 动画或 JavaScript 动态控制样式来实现。以下是几种常见的方法:

使用 CSS 动画
通过定义 CSS 关键帧动画,结合 Vue 的动态类绑定实现子弹循环移动效果。

<template>
<div class="bullet-container">
<div class="bullet" :style="{ left: position + 'px' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
position: 0
};
},
mounted() {
setInterval(() => {
this.position += 10;
if (this.position > 500) {
this.position = 0;
}
}, 100);
}
};
</script>
<style>
.bullet-container {
position: relative;
width: 500px;
height: 50px;
border: 1px solid #ccc;
}
.bullet {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
}
</style>
使用 Vue Transition
通过 Vue 的 <transition> 组件结合 CSS 过渡效果实现子弹循环动画。
<template>
<div class="bullet-container">
<transition name="bullet" mode="out-in">
<div v-if="showBullet" class="bullet"></div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
showBullet: true
};
},
mounted() {
setInterval(() => {
this.showBullet = !this.showBullet;
}, 1000);
}
};
</script>
<style>
.bullet-container {
position: relative;
width: 500px;
height: 50px;
border: 1px solid #ccc;
}
.bullet {
position: absolute;
width: 20px;
height: 20px;
background-color: blue;
border-radius: 50%;
}
.bullet-enter-active, .bullet-leave-active {
transition: all 1s;
}
.bullet-enter, .bullet-leave-to {
transform: translateX(500px);
}
</style>
使用第三方动画库
结合 GSAP 或 Anime.js 等动画库实现更复杂的子弹循环动画效果。
<template>
<div class="bullet-container">
<div ref="bullet" class="bullet"></div>
</div>
</template>
<script>
import { gsap } from 'gsap';
export default {
mounted() {
const bullet = this.$refs.bullet;
gsap.to(bullet, {
x: 500,
duration: 1,
repeat: -1,
yoyo: true
});
}
};
</script>
<style>
.bullet-container {
position: relative;
width: 500px;
height: 50px;
border: 1px solid #ccc;
}
.bullet {
position: absolute;
width: 20px;
height: 20px;
background-color: green;
border-radius: 50%;
}
</style>
以上方法均可实现子弹循环动画效果,根据项目需求选择合适的方式。CSS 动画适合简单效果,Vue Transition 适合组件过渡,第三方库适合复杂动画场景。






