Vue 3 是一个现代化的前端框架,而 GSAP(GreenSock Animation Platform)是一个功能强大、性能优越的动画库。将 Vue 3 与 GSAP 集成可以为开发者提供一种高效的方式来创建复杂的交互式动画。
在这篇文章中,我们将深入探讨如何在 Vue 3 中集成 GSAP,并通过实际示例展示如何制作高级动画效果。以下是具体的内容解析:
setup
函数,允许开发者以更灵活的方式组织代码逻辑。首先需要安装 GSAP 库:
npm install gsap
如果需要使用额外的插件(如 ScrollTrigger),可以通过以下命令安装:
npm install gsap@^3 --save
npm install @gsap/scrolltrigger
在 Vue 3 中可以通过 import
语句引入 GSAP:
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
// 注册 ScrollTrigger 插件
gsap.registerPlugin(ScrollTrigger);
我们可以通过 GSAP 创建一个淡入动画,当页面加载时触发。
HTML 结构
<template>
<div class="box" ref="box"></div>
</template>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
opacity: 0; /* 初始透明度为 0 */
}
</style>
Vue 3 组件逻辑
<script>
import { onMounted, ref } from 'vue';
import { gsap } from 'gsap';
export default {
setup() {
const box = ref(null);
onMounted(() => {
gsap.to(box.value, {
duration: 2,
opacity: 1, // 淡入效果
ease: 'power1.inOut' // 缓动函数
});
});
return { box };
}
};
</script>
我们可以结合 ScrollTrigger 实现当用户滚动到某个元素时触发动画的效果。
HTML 结构
<template>
<div>
<div class="content" ref="content">Scroll to reveal me!</div>
</div>
</template>
<style>
.content {
width: 200px;
height: 200px;
background-color: blue;
color: white;
text-align: center;
line-height: 200px;
opacity: 0;
transform: translateY(50px); /* 初始位置偏移 */
}
</style>
Vue 3 组件逻辑
<script>
import { onMounted, ref } from 'vue';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
export default {
setup() {
const content = ref(null);
onMounted(() => {
gsap.to(content.value, {
scrollTrigger: {
trigger: content.value, // 触发元素
start: 'top 80%', // 动画开始条件
end: 'bottom 20%', // 动画结束条件
scrub: true // 平滑滚动效果
},
duration: 1.5,
opacity: 1,
y: 0, // 移动到初始位置
ease: 'elastic.out(1, 0.3)' // 弹性缓动
});
});
return { content };
}
};
</script>
GSAP 提供了 Timeline
功能,可以用来创建一系列按顺序执行的动画。
HTML 结构
<template>
<div>
<div class="circle" ref="circle"></div>
<div class="square" ref="square"></div>
</div>
</template>
<style>
.circle {
width: 50px;
height: 50px;
background-color: green;
border-radius: 50%;
}
.square {
width: 100px;
height: 100px;
background-color: orange;
margin-top: 20px;
}
</style>
Vue 3 组件逻辑
<script>
import { onMounted, ref } from 'vue';
import { gsap } from 'gsap';
export default {
setup() {
const circle = ref(null);
const square = ref(null);
onMounted(() => {
const timeline = gsap.timeline();
timeline.from(circle.value, {
duration: 1,
scale: 0, // 圆形从无到有
ease: 'back.out(1.7)'
})
.from(square.value, {
duration: 1,
x: -200, // 方块从左侧进入
ease: 'power2.inOut'
}, '-=0.5'); // 与上一个动画重叠 0.5 秒
});
return { circle, square };
}
};
</script>
transform
和 opacity
)来提升性能。ScrollTrigger.kill()
或 timeline.kill()
来释放资源。通过 Vue 3 和 GSAP 的集成,开发者可以轻松实现复杂的动画效果。无论是简单的淡入淡出,还是基于滚动的动态动画,甚至是时间轴控制的多阶段动画,GSAP 都提供了强大的工具支持。结合 Vue 3 的组合式 API,代码结构更加清晰,维护也更加方便。