vue 实现文字动画
Vue 实现文字动画的方法
Vue 提供了多种方式实现文字动画效果,可以通过内置的 Transition 组件、第三方动画库或结合 CSS 动画实现。
使用 Vue Transition 组件
Vue 的 Transition 组件可以为元素添加进入/离开的过渡效果。通过定义 CSS 过渡类名实现文字动画效果。
<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: true
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>
使用 CSS 动画
直接使用 CSS @keyframes 定义动画,通过 Vue 动态绑定 class 触发动画。
<template>
<p :class="{ 'text-animate': animate }">Animated Text</p>
<button @click="animate = !animate">Animate</button>
</template>
<script>
export default {
data() {
return {
animate: false
}
}
}
</script>
<style>
.text-animate {
animation: bounce 0.5s;
}
@keyframes bounce {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
</style>
使用第三方动画库
安装并引入动画库如 animate.css,通过 Vue 动态添加类名实现丰富动画效果。
npm install animate.css
<template>
<p :class="['animated', { 'bounce': animate }]">Bouncing Text</p>
<button @click="animate = !animate">Toggle Bounce</button>
</template>
<script>
import 'animate.css/animate.min.css'
export default {
data() {
return {
animate: false
}
}
}
</script>
使用 GSAP 实现高级动画
GSAP 提供了强大的动画控制能力,适合复杂文字动画场景。
npm install gsap
<template>
<p ref="textElement">GSAP Animated Text</p>
<button @click="animateText">Animate</button>
</template>
<script>
import { gsap } from 'gsap'
export default {
methods: {
animateText() {
gsap.to(this.$refs.textElement, {
duration: 1,
x: 100,
rotation: 360,
ease: 'bounce.out'
})
}
}
}
</script>
逐字显示动画
通过计算属性实现文字逐个显示的效果。

<template>
<p>{{ displayedText }}</p>
</template>
<script>
export default {
data() {
return {
fullText: 'Hello Vue.js!',
currentText: '',
index: 0
}
},
computed: {
displayedText() {
return this.currentText
}
},
mounted() {
this.typeWriter()
},
methods: {
typeWriter() {
if (this.index < this.fullText.length) {
this.currentText += this.fullText.charAt(this.index)
this.index++
setTimeout(this.typeWriter, 100)
}
}
}
}
</script>
每种方法适用于不同场景,Transition 组件适合简单过渡效果,CSS 动画适合基础动画,第三方库提供丰富预设,GSAP 适合复杂动画控制,逐字显示适合打字机效果。






