Vue 中动画如何实现?
在 Vue 中实现动画非常方便,Vue 提供了专门的 <transition> 和 <transition-group> 组件,用于给元素或组件添加进入、离开、切换的过渡动画。
一、最基础的动画:使用 <transition> 实现显示/隐藏过渡
<template>
<div>
<button @click="show = !show">切换</button>
<transition name="fade">
<p v-if="show">Hello Vue 动画</p>
</transition>
</div>
</template>
<script setup>
import { ref } from 'vue';
const show = ref(true);
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>
二、自定义动画名(完整类名列表)
当你使用 <transition name="xxx">,Vue 会自动加上这些类名:
| 阶段 | 类名 |
|---|---|
| 进入开始 | xxx-enter-from |
| 进入激活中 | xxx-enter-active |
| 进入完成 | xxx-enter-to |
| 离开开始 | xxx-leave-from |
| 离开激活中 | xxx-leave-active |
| 离开完成 | xxx-leave-to |
三、使用动画库(如 Animate.css)
npm install animate.css
<template>
<transition
enter-active-class="animate__animated animate__fadeIn"
leave-active-class="animate__animated animate__fadeOut">
<p v-if="show">带动画库的效果</p>
</transition>
</template>
<script setup>
import 'animate.css';
import { ref } from 'vue';
const show = ref(true);
</script>
四、多个元素动画:使用 <transition-group>
<template>
<div>
<button @click="addItem">添加</button>
<transition-group name="list" tag="ul">
<li v-for="item in items" :key="item">{{ item }}</li>
</transition-group>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([1, 2, 3]);
function addItem() {
items.value.push(Date.now());
}
</script>
<style>
.list-enter-active, .list-leave-active {
transition: all 0.5s;
}
.list-enter-from, .list-leave-to {
opacity: 0;
transform: translateY(20px);
}
</style>
五、用 JavaScript 实现动画回调(不写 CSS)
<transition
@before-enter="beforeEnter"
@enter="enter"
@leave="leave">
<div v-if="show">JS控制动画</div>
</transition>
<script setup>
import { ref } from 'vue';
const show = ref(true);
function beforeEnter(el) {
el.style.opacity = 0;
}
function enter(el, done) {
setTimeout(() => {
el.style.transition = 'opacity 1s';
el.style.opacity = 1;
done();
}, 0);
}
function leave(el, done) {
el.style.transition = 'opacity 1s';
el.style.opacity = 0;
setTimeout(done, 1000);
}
</script>
六、配合 Vue Router 实现页面切换动画
<template>
<transition name="fade" mode="out-in">
<router-view />
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>
总结
| 用法 | 场景 | 组件 |
|---|---|---|
<transition> |
单元素或组件进入/离开 | 普通过渡 |
<transition-group> |
列表动画 | v-for 列表 |
| JavaScript 钩子 | 动画逻辑更复杂时 | 自定义控制 |
| 第三方库 | 快速实现好看的动画 | Animate.css / GSAP |
| Vue Router | 页面切换动画 | <router-view> 配合 <transition> |
浙公网安备 33010602011771号