vue实现小球弹入
Vue 实现小球弹入动画
使用 Vue 实现小球弹入动画可以通过 CSS 动画或 JavaScript 动画库(如 GSAP)来完成。以下是两种常见的方法:
使用 CSS 过渡和动画
在 Vue 模板中定义一个小球元素,通过动态类名或内联样式控制其动画效果。
<template>
<div class="ball" :class="{ 'bounce-in': isBouncing }" @click="toggleBounce"></div>
</template>
<script>
export default {
data() {
return {
isBouncing: false
};
},
methods: {
toggleBounce() {
this.isBouncing = !this.isBouncing;
}
}
};
</script>
<style>
.ball {
width: 50px;
height: 50px;
background-color: #42b983;
border-radius: 50%;
transition: transform 0.5s ease;
}
.bounce-in {
transform: translateY(-100px);
}
</style>
使用 GSAP 实现高级动画
GSAP 是一个强大的动画库,可以更灵活地控制动画效果。
<template>
<div ref="ball" class="ball" @click="bounce"></div>
</template>
<script>
import { gsap } from 'gsap';
export default {
methods: {
bounce() {
gsap.to(this.$refs.ball, {
y: -100,
duration: 0.5,
ease: "bounce.out"
});
}
}
};
</script>
<style>
.ball {
width: 50px;
height: 50px;
background-color: #42b983;
border-radius: 50%;
}
</style>
使用 Vue 的 <transition> 组件
Vue 的 <transition> 组件可以方便地实现进入和离开动画。
<template>
<button @click="showBall = !showBall">Toggle Ball</button>
<transition
@before-enter="beforeEnter"
@enter="enter"
@leave="leave"
>
<div v-if="showBall" class="ball"></div>
</transition>
</template>
<script>
export default {
data() {
return {
showBall: false
};
},
methods: {
beforeEnter(el) {
el.style.transform = 'translateY(-100px)';
el.style.opacity = 0;
},
enter(el, done) {
const animation = el.animate(
[
{ transform: 'translateY(-100px)', opacity: 0 },
{ transform: 'translateY(0)', opacity: 1 }
],
{ duration: 500 }
);
animation.onfinish = done;
},
leave(el, done) {
const animation = el.animate(
[
{ transform: 'translateY(0)', opacity: 1 },
{ transform: 'translateY(-100px)', opacity: 0 }
],
{ duration: 500 }
);
animation.onfinish = done;
}
}
};
</script>
<style>
.ball {
width: 50px;
height: 50px;
background-color: #42b983;
border-radius: 50%;
margin-top: 20px;
}
</style>
以上方法可以根据需求选择,CSS 过渡适合简单动画,GSAP 适合复杂动画,而 Vue 的 <transition> 组件则适合组件级别的动画控制。







