vue 实现动效
使用 Vue 实现动画效果的方法
Vue 提供了多种方式实现动画效果,包括内置的过渡组件、第三方动画库以及直接操作 CSS 或 JavaScript 动画。
使用 Vue 内置 <transition> 组件
Vue 的 <transition> 组件可以方便地添加进入/离开动画。
<template>
<button @click="show = !show">Toggle</button>
<transition name="fade">
<p v-if="show">Hello Vue!</p>
</transition>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用 CSS 动画
除了过渡效果,还可以直接使用 CSS @keyframes 定义动画。
<template>
<button @click="animate = !animate">Animate</button>
<div :class="{ 'bounce': animate }">Bounce Effect</div>
</template>
<script>
export default {
data() {
return {
animate: false
}
}
}
</script>
<style>
.bounce {
animation: bounce 0.5s;
}
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-20px); }
}
</style>
使用 JavaScript 动画
如果需要更精细的控制,可以使用 Velocity.js 或 GSAP 等库结合 Vue 实现动画。
<template>
<button @click="animateBox">Animate with GSAP</button>
<div ref="box" class="box"></div>
</template>
<script>
import { gsap } from 'gsap';
export default {
methods: {
animateBox() {
gsap.to(this.$refs.box, {
x: 100,
rotation: 360,
duration: 1
});
}
}
}
</script>
<style>
.box {
width: 50px;
height: 50px;
background: #42b983;
}
</style>
使用第三方动画库
Animate.css 是一个流行的 CSS 动画库,可以轻松集成到 Vue 项目中。
<template>
<button @click="show = !show">Toggle Animate.css</button>
<transition
enter-active-class="animate__animated animate__bounceIn"
leave-active-class="animate__animated animate__bounceOut"
>
<p v-if="show">Animate.css Example</p>
</transition>
</template>
<script>
import 'animate.css';
export default {
data() {
return {
show: false
}
}
}
</script>
列表动画(<transition-group>)
如果需要为列表元素添加动画,可以使用 <transition-group>。

<template>
<button @click="addItem">Add Item</button>
<button @click="removeItem">Remove Item</button>
<transition-group name="list" tag="ul">
<li v-for="item in items" :key="item">{{ item }}</li>
</transition-group>
</template>
<script>
export default {
data() {
return {
items: [1, 2, 3],
nextNum: 4
}
},
methods: {
addItem() {
this.items.push(this.nextNum++);
},
removeItem() {
this.items.pop();
}
}
}
</script>
<style>
.list-enter-active, .list-leave-active {
transition: all 0.5s;
}
.list-enter, .list-leave-to {
opacity: 0;
transform: translateY(30px);
}
</style>
这些方法可以灵活组合使用,以满足不同的动画需求。






