gsap-frameworks
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGSAP with Vue, Svelte, and Other Frameworks
GSAP 在 Vue、Svelte 及其他框架中的使用
When to Use This Skill
何时使用本技能
Apply when writing or reviewing GSAP code in Vue (or Nuxt), Svelte (or SvelteKit), or other component frameworks that use a lifecycle (mounted/unmounted). For React specifically, use gsap-react (useGSAP hook, gsap.context()).
Related skills: For tweens and timelines use gsap-core and gsap-timeline; for scroll-based animation use gsap-scrolltrigger; for React use gsap-react.
当你在Vue(或Nuxt)、Svelte(或SvelteKit)或其他使用生命周期(挂载/卸载)的组件框架中编写或审核GSAP代码时,可应用本技能。针对React框架,请使用gsap-react(useGSAP钩子、gsap.context())。
相关技能: 补间动画与时间轴请使用gsap-core和gsap-timeline;滚动类动画请使用gsap-scrolltrigger;React框架请使用gsap-react。
Principles (All Frameworks)
通用原则(所有框架)
- Create tweens and ScrollTriggers after the component’s DOM is available (e.g. onMounted, onMount).
- Kill or revert them in the unmount (or equivalent) cleanup so nothing runs on detached nodes and there are no leaks.
- Scope selectors to the component root so and similar only match elements inside that component, not the rest of the page.
.box
- 在组件DOM可用后(如onMounted、onMount阶段)创建补间动画和ScrollTrigger实例。
- 在卸载(或等效阶段)时销毁或还原这些实例,避免已脱离节点的动画继续运行,防止内存泄漏。
- 为选择器设置组件根作用域,确保这类选择器仅匹配当前组件内的元素,而非页面中的其他元素。
.box
Vue 3 (Composition API)
Vue 3(组合式API)
Use onMounted to run GSAP after the component is in the DOM. Use onUnmounted to clean up.
javascript
import { onMounted, onUnmounted, ref } from "vue";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger); // once per app, e.g. in main.js
export default {
setup() {
const container = ref(null);
let ctx;
onMounted(() => {
if (!container.value) return;
ctx = gsap.context(() => {
gsap.to(".box", { x: 100, duration: 0.6 });
gsap.from(".item", { autoAlpha: 0, y: 20, stagger: 0.1 });
}, container.value);
});
onUnmounted(() => {
ctx?.revert();
});
return { container };
}
};- ✅ gsap.context(scope) — pass the container ref (e.g. ) as the second argument so selectors like
container.valueare scoped to that root. All animations and ScrollTriggers created inside the callback are tracked and reverted when ctx.revert() is called..item - ✅ onUnmounted — always call ctx.revert() so tweens and ScrollTriggers are killed and inline styles reverted.
使用onMounted在组件挂载到DOM后运行GSAP,使用onUnmounted进行清理。
javascript
import { onMounted, onUnmounted, ref } from "vue";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger); // 全局注册一次,例如在main.js中
export default {
setup() {
const container = ref(null);
let ctx;
onMounted(() => {
if (!container.value) return;
ctx = gsap.context(() => {
gsap.to(".box", { x: 100, duration: 0.6 });
gsap.from(".item", { autoAlpha: 0, y: 20, stagger: 0.1 });
}, container.value);
});
onUnmounted(() => {
ctx?.revert();
});
return { container };
}
};- ✅ gsap.context(scope) —— 传入容器ref(如)作为第二个参数,使
container.value这类选择器的作用域限定在该根节点内。回调中创建的所有动画和ScrollTrigger实例都会被追踪,调用**ctx.revert()**时会被还原。.item - ✅ onUnmounted —— 务必调用ctx.revert(),销毁补间动画和ScrollTrigger实例并还原内联样式。
Vue 3 (script setup)
Vue 3(script setup语法)
Same idea with and refs:
<script setup>javascript
<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
const container = ref(null);
let ctx;
onMounted(() => {
if (!container.value) return;
ctx = gsap.context(() => {
gsap.to(".box", { x: 100 });
gsap.from(".item", { autoAlpha: 0, stagger: 0.1 });
}, container.value);
});
onUnmounted(() => {
ctx?.revert();
});
</script>
<template>
<div ref="container">
<div class="box">Box</div>
<div class="item">Item</div>
</div>
</template>使用和ref的实现思路一致:
<script setup>javascript
<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
const container = ref(null);
let ctx;
onMounted(() => {
if (!container.value) return;
ctx = gsap.context(() => {
gsap.to(".box", { x: 100 });
gsap.from(".item", { autoAlpha: 0, stagger: 0.1 });
}, container.value);
});
onUnmounted(() => {
ctx?.revert();
});
</script>
<template>
<div ref="container">
<div class="box">Box</div>
<div class="item">Item</div>
</div>
</template>Svelte
Svelte
Use onMount to run GSAP after the DOM is ready. Use the returned cleanup function from onMount (or track the context and clean up in a reactive block / component destroy) to revert. Svelte 5 uses a different lifecycle; the same principle applies: create in “mounted” and revert in “destroyed.”
javascript
<script>
import { onMount } from "svelte";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
let container;
onMount(() => {
if (!container) return;
const ctx = gsap.context(() => {
gsap.to(".box", { x: 100 });
gsap.from(".item", { autoAlpha: 0, stagger: 0.1 });
}, container);
return () => ctx.revert();
});
</script>
<div bind:this={container}>
<div class="box">Box</div>
<div class="item">Item</div>
</div>- ✅ bind:this={container} — get a reference to the root element so you can pass it to gsap.context(scope).
- ✅ return () => ctx.revert() — Svelte’s onMount can return a cleanup function; call ctx.revert() there so cleanup runs when the component is destroyed.
使用onMount在DOM准备就绪后运行GSAP,利用onMount返回的清理函数(或追踪上下文并在响应式块/组件销毁时清理)进行还原。Svelte 5的生命周期有所不同,但核心原则一致:在“挂载”阶段创建实例,在“销毁”阶段还原。
javascript
<script>
import { onMount } from "svelte";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
let container;
onMount(() => {
if (!container) return;
const ctx = gsap.context(() => {
gsap.to(".box", { x: 100 });
gsap.from(".item", { autoAlpha: 0, stagger: 0.1 });
}, container);
return () => ctx.revert();
});
</script>
<div bind:this={container}>
<div class="box">Box</div>
<div class="item">Item</div>
</div>- ✅ bind:this={container} —— 获取根元素的引用,以便传递给gsap.context(scope)。
- ✅ return () => ctx.revert() —— Svelte的onMount可以返回一个清理函数,在此处调用ctx.revert(),确保组件销毁时自动执行清理。
Scoping Selectors
选择器作用域设置
Do not use global selectors that can match elements outside the current component. Always pass the scope (container element or ref) as the second argument to gsap.context(callback, scope) so that any selector run inside the callback is limited to that subtree.
- ✅ gsap.context(() => { gsap.to(".box", ...) }, containerRef) — is only searched inside
.box.containerRef - ❌ Running gsap.to(".box", ...) without a context scope in a component can affect other instances or the rest of the page.
请勿使用能匹配当前组件外元素的全局选择器。务必将作用域(容器元素或ref)作为第二个参数传递给gsap.context(callback, scope),确保回调内的所有选择器仅在该子树内查找元素。
- ✅ gsap.context(() => { gsap.to(".box", ...) }, containerRef) —— 仅在
.box内部查找。containerRef - ❌ 在组件中直接运行**gsap.to(".box", ...)**而不设置上下文作用域,可能会影响其他组件实例或页面中的其他元素。
ScrollTrigger Cleanup
ScrollTrigger 清理
ScrollTrigger instances are created when you use the config on a tween/timeline or ScrollTrigger.create(). They are included in gsap.context() and reverted when you call ctx.revert(). So:
scrollTrigger- Create ScrollTriggers inside the same gsap.context() callback you use for tweens.
- Call ScrollTrigger.refresh() after layout changes (e.g. after data loads) that affect trigger positions; in Vue/Svelte that often means after the DOM updates (e.g. nextTick in Vue, tick in Svelte, or after async content load).
当你在补间/时间轴的配置中使用,或调用**ScrollTrigger.create()时,会创建ScrollTrigger实例。这些实例会被包含在gsap.context()中,调用ctx.revert()**时会被还原。因此:
scrollTrigger- 在用于补间动画的同一个**gsap.context()**回调中创建ScrollTrigger实例。
- 当布局变化(如数据加载完成)影响触发位置时,调用ScrollTrigger.refresh();在Vue/Svelte中,通常需要在DOM更新后执行(如Vue的nextTick、Svelte的tick,或异步内容加载完成后)。
When to Create vs Kill
创建与销毁时机
| Lifecycle | Action |
|---|---|
| Mounted | Create tweens and ScrollTriggers inside gsap.context(scope). |
| Unmount / Destroy | Call ctx.revert() so all animations and ScrollTriggers in that context are killed and inline styles reverted. |
Do not create GSAP animations in the component’s setup or in a synchronous top-level script that runs before the root element exists. Wait for onMounted / onMount (or equivalent) so the container ref is in the DOM.
| 生命周期阶段 | 操作 |
|---|---|
| 挂载完成 | 在**gsap.context(scope)**内部创建补间动画和ScrollTrigger实例。 |
| 卸载 / 销毁 | 调用ctx.revert(),销毁该上下文中的所有动画和ScrollTrigger实例,并还原内联样式。 |
请勿在组件的setup阶段,或DOM根元素存在前运行的同步顶层脚本中创建GSAP动画。请等待onMounted / onMount(或等效阶段),确保容器ref已挂载到DOM中。
Do Not
禁止操作
- ❌ Create tweens or ScrollTriggers before the component is mounted (e.g. in setup without onMounted); the DOM nodes may not exist yet.
- ❌ Use selector strings without a scope (pass the container to gsap.context() as the second argument) so selectors don’t match elements outside the component.
- ❌ Skip cleanup; always call ctx.revert() in onUnmounted / onMount’s return so animations and ScrollTriggers are killed when the component is destroyed.
- ❌ Register plugins inside a component body that runs every render (it doesn't hurt anything, it's just wasteful); register once at app level.
- ❌ 在组件挂载前创建补间或ScrollTrigger实例(如未使用onMounted的setup阶段);此时DOM节点可能尚未存在。
- ❌ 不设置作用域就使用选择器字符串(需将容器作为第二个参数传入gsap.context()),避免选择器匹配到组件外的元素。
- ❌ 跳过清理步骤;务必在onUnmounted / onMount的返回函数中调用ctx.revert(),确保组件销毁时动画和ScrollTrigger实例被销毁。
- ❌ 在每次渲染都会执行的组件内部注册插件(虽无危害,但会造成资源浪费);请在应用全局层面注册一次。
Learn More
更多学习资源
- gsap-react skill for React-specific patterns (useGSAP, contextSafe).
- React框架专属模式(useGSAP、contextSafe)请查看gsap-react技能。