Lifecycle implementation
Read this to implement the five phases for pages and components without layout shift.
The contract
mount → initial state → intro → settled → outro → end state → unmount
One controller owns a node from mount to unmount and exposes one current phase:
- Initial state. In the DOM, final size reserved, measured, start values applied, not yet shown.
- Intro. One timeline from initial values to settled.
- Settled. Visible, stable, interactive, and controlled by normal CSS.
- Outro. Still in the DOM while one timeline moves it toward removal.
- End state. Still in the DOM, final values applied, completion run once. Safe to remove.
The user's request defines how each phase looks. If it only describes an intro or outro, implement the other phases as the minimum needed to enter and leave cleanly.
Store the current phase in a data attribute on the owned node, or in a ref mirrored to one. Do not infer it from opacity, DOM presence, or timeline progress.
Setup and Vue lifecycle
Create one client-only module that imports GSAP and only the plugins the project uses, registers them once, and exports them. In Nuxt that is the useGSAP composable from gsap-frameworks or a .client.ts plugin. Other modules import from it.
Give every owner a gsap.context scoped to its root:
- Components: create it in
onMountedwith the template ref as scope and revert it inonBeforeUnmount. Under keepalive, revert inonDeactivatedand rebuild inonActivated. Both unmount hooks run before a leave transition finishes, so neither is a place for outro work. - Pages: the page's context owns settled-state work and reverts at leave start. The transition module owns a second context per
elfor the intro and the outro, created inonBeforeEnteroronLeaveand reverted inonAfterEnteroronAfterLeave. - Selectors inside a context match only inside its root.
revert()kills every tween, trigger, and split it created and restores inline styles. - Wrap event handlers and delayed callbacks that create GSAP work in
context.addso they belong to the context. - Store listeners, observers, and timers next to the context and remove them in the same cleanup.
Wait for the DOM before measuring. After a reactive change that alters the template, await nextTick() before reading sizes or refreshing ScrollTrigger. Content inside <ClientOnly> appears only after mount; watch its template ref.
Inside <NuxtPage> a page's onMounted runs when its Suspense resolves: on navigation that is at leave start or after the leave depending on mode, and on first load it is after hydration. Component-level setup belongs there; page-level phases belong to the transition hooks.
Write setup so it is correct when it runs more than once on the same node. onActivated under keepalive, development hot reload, and a presence controller re-showing content all hand you a node that already holds settled values. Write initial state explicitly with set or fromTo rather than a from tween that trusts a fresh node, and make cleanup leave the node readable.
Initial state
Build the final layout with normal CSS first. The initial state changes appearance, not layout. The element that owns geometry must exist before the animated node does.
- Mount content before measuring or animating it.
- Give images and media dimensions or an aspect ratio;
<NuxtImg>and<NuxtPicture>takewidthandheight. - Reserve async regions with a wrapper when their size is known. A
useAsyncDataregion that resolves after mount is a component with its own controller. - Prefer transforms,
autoAlpha, masks, or clipping, which keep the layout box.
If the effect changes width, height, or position:
- Animate a transform on an inner element while an outer wrapper holds the settled size.
- For a real expand or collapse, measure start and end sizes first, animate the wrapper, and decide how surrounding content moves.
- For layout-to-layout changes, use Flip:
captureLayoutfrom theanimaxxingskill'sreferences/recipes/layout-flip.md, change the state,await nextTick(),play(). Av-foritem Vue removes cannot animate out; hide it with a class orv-showif it must. - When old and new content share one region, reserve the parent and overlap the children so only the parent affects layout.
Content must stay readable without JavaScript. The pre-paint rule in SSR and first paint is the only sanctioned way to hide before the intro.
Initialization and recovery
Apply the initialization contract whenever content starts hidden. It includes recovery ordering, indexing/performance limits, and failure checks.
- Use the early head script described in SSR and first paint, with its own timer. Preserve SSR HTML;
ClientOnly/ssr: falsecannot supply missing page content without JavaScript. - Register rollback before first-load
onMountedsetup and before navigation'sonBeforeEnterwrites. Keep the deadline through preparation andonEntertimeline construction. Catch failures in both hooks and deferred callbacks; claiming the document does not cancel recovery. - Keep per-element records outside the page context that Nuxt may revert at leave start. Wrap each hook's
doneonce and release it on completion, recovery, or cancellation as appropriate. A cancelled enter must not run staleonAfterEnterfocus or reveal a leaving page. - Invalidate before leave, unmount, and keepalive deactivation; do not reveal keepalive storage. A real activation starts a new visit after layout is available. Persistent layouts/chrome retain their own records, including when
pageTransition: false.
Intro and settled
Write reusable intro and outro builders only when behavior repeats. Each returns a timeline so the controller can compose, kill, reverse, or await it, and each takes the done callback when a Vue hook drives it.
- Make settled the source of truth. It must not depend on a paused timeline.
- Clear temporary transform, visibility, transition, and
will-changestyles once settled. - Run intro completion and settled callbacks once, including under reduced motion.
- On rapid state changes, replace, kill, or reverse the active timeline. Do not stack conflicting tweens.
- Update assistive text and state immediately. Animate the visual, not the meaning.
Outro and end state
Start the outro from current rendered values. Keep the node in the DOM, laid out, and owned until the timeline completes.
- Reject duplicate outro requests or define which wins.
- If an intro is running, reverse it only when the outro is its exact inverse. Otherwise kill it and build the outro from current values.
- Disable pointer events when the visual can no longer support them, without removing the layout box.
- Run end-state work once. Only then call
done, remove, hide, or navigate. - Kill the active timeline on cleanup, but do not erase state a cover still needs.
- No
v-iftoggle,v-showoff,display: none, or DOM removal before the outro completes.
Conditional show and hide
Vue's <Transition> is the presence controller. Wrap the conditional node in <Transition :css="false"> with the same JavaScript hooks pages use. It should:
- Show into initial state in
onBeforeEnter, before the intro inonEnter. - Stay in the DOM through settled and through
onLeaveuntildone. - Keep the active timeline where the hooks can kill it.
- Keep all five phases under reduced motion and still call
done.
Choose the toggle by what re-show during an outro should do. With v-show, the same element stays: Vue fires onLeaveCancelled and starts onEnter on it, so reverse is possible when it gives the intended intro. With v-if, Vue finishes the pending leave at once and mounts a fresh node, so build a fresh intro from initial state. Wrap a component only if it has a single root element.
appear is safe only on content that is not server-rendered. On SSR output it wraps the child in <template> and hides it until hydration.
Use <TransitionGroup> for lists. The same hooks run once per item with that item's el; read a data-index attribute for stagger, give every item a key, and set :css="false". Its move animation is CSS-only, so use Flip when moves must be sequenced with GSAP. Pick one per list; a move-class and a Flip on the same items fight.
When content in a shared region changes size, decide who owns the region's geometry before showing either child. Overlap old and new inside a reserved wrapper, or animate a measured wrapper between known sizes. Do not let hide then show push surrounding content twice.
Do not use presence for content that can simply appear, or for page content <NuxtPage> already manages.
- Focus a panel when its intro completes, not when it is shown. An element at
visibility: hiddenrefuses focus silently, andautoAlpha: 0is exactly that. Reduced motion completes synchronously, so the focus still lands. - A dialog or menu that locks scroll, traps focus, or adds a key listener undoes all of it in its end-state callback, and again in
onBeforeUnmountoronDeactivatedin case its page leaves mid-open.
Reduced and responsive motion
The OS preference is the default. Add a site override only if the product needs one.
Every effect needs initial, settled, and end states under reduced motion. Do not just shorten a disorienting effect. Skip travel, rotation, scale, parallax, and scrambling unless essential. A zero-duration timeline or an immediate set still fires completion, and every Vue hook still calls done.
Use gsap.matchMedia() for responsive and reduced-motion variants that must rebuild when conditions change. Create it inside the owner's context so it reverts with the owner.
A site-level override is not a media query, so matchMedia cannot see it. Keep it in useState or a store, read it in a shared prefersReducedMotion() helper that every builder consults, mirror it as a root attribute so CSS can key on it, and rebuild matchMedia setups when it changes. experimental.viewTransition: true already skips the browser side under the OS preference.
Scroll
Use gsap-scrolltrigger for the API; these rules cover route lifetime and measurement.
- Create triggers in document order. Refresh after fonts, images, or async data change layout, after
await nextTick(), and after Nuxt's post-transition scroll. - Create triggers inside the owning context. Do not kill all triggers globally when one page leaves.
- Nuxt scrolls after the outro and one frame into the intro. Create page-level triggers in
onAfterEnter, or afterpage:transition:finishplus a frame, and let them evaluate on creation so targets above the restored position are not left hidden. - A page in keepalive storage measures zero. Kill triggers in
onDeactivatedand create them again inonActivatedafter the scroll settles. - Reverting a pinned trigger removes its spacer. That happens at leave start, so hold the wrapper's height through the outro.
- Reverting a scrubbed trigger's animation can leave start values inline on its targets, such as a zeroed
transform,opacity: 1, orvisibility: inherit. It always does withinvalidateOnRefreshand can for a plainto()in a pinned timeline. When a re-show, a reused page, or another effect needs the targets clean, record their inline motion properties at setup and restore them after the revert;clearPropsalso resets GSAP's cached transform. - A
will-changewritten from anonTogglecallback is outside the context and survives its revert. Write it as a plain style and undo it in cleanup, or write it before the trigger is created.
Under reduced motion, go straight from initial to settled without unnecessary triggers. Keep outro and end callbacks that control done or removal.
Text
Use SplitText when the effect needs per-character, word, or line targets.
- For character splits, keep scoped
font-kerning: none; text-rendering: optimizeSpeedbefore, during, and after revert, including reduced motion. Wrappers disrupt kerning and can cause horizontal snapping; use words/lines if natural kerning is essential. See SplitText limitations. - Apparent weight changes can be clipped ink: check computed fonts/readiness, then mask edges, punctuation, and descenders. For confirmed clipping, add scoped mask padding with compensating negative margins; verify spacing and both hidden endpoints before trying compositing workarounds.
- Keep reading accessible with the plugin's ARIA support. If text contains links or controls, keep an unsplit accessible version instead of hiding them.
- Use word-aware wrapping for character animation. Use auto re-split for line animation that must survive width or font changes.
- When line measurement needs fonts, bound the wait or auto-split preparation by the initialization deadline. Reserve settled height before splitting if wrappers could shift layout.
- With
autoSplit, build the animation insideonSplitand return it. The plugin records the playhead before a re-split, restores it on the new lines, and waits for fonts itself. - A split heading takes its timing from the page phase, not its own clock. Give it its own pre-paint rule rather than marking it as a page target, or the page's stagger and the split's rise fight over one element.
- Split after hydration, never in server-rendered markup. Revert splits on interruption, on leave, and on deactivate. Do not leave wrapper spans in stale content.
Revert when the owning phase no longer needs the split. Compare glyph appearance, character positions, wrapping, and height immediately before/after cleanup at desktop/mobile widths, with reduced motion and interruption. Stable boxes alone do not prove stable ink; distinguish subpixel rounding from visible movement.
Interaction
Pointer motion needs keyboard parity. Pair hover with focus on interactive elements. Do not animate a non-interactive element like a control.
Keep gestures bounded, provide a non-gesture path, and dispose of interaction plugins with their owner. See gsap-plugins for Draggable, Observer, and Flip APIs.
Layout stability and performance
- Prefer
x,y, scale, rotation, andautoAlphaover layout properties. - Use
clip-path, filters, and variable-font axes deliberately; they can cost paint or shift layout. - Batch reads before writes.
- The stable wrapper's box should not jump between mount, initial, settled, outro, end, and unmount. Intentional transforms move pixels; layout boxes do not.
- Set
will-changejust before animating and clear it after. Do not promote everything. - Do not animate hundreds of nodes at once. Reduce targets, batch, or virtualize.
- Do not add a CSS transition on a property GSAP controls, and do not leave Vue transition classes active on a GSAP-driven root;
css: falseprevents that.