In the previous lesson you saw that Vue updates the DOM by comparing the previous virtual node tree with the new one and applying only the differences. The result is correct and fast, but instantaneous: the new booking notice appears out of nowhere, the user menu pops up from nothing, a cancelled booking vanishes from the list before the eye can follow it and one screen replaces another with no transition. Animations used well are not decoration: they help the user understand what has changed and where it has gone. Vue includes two components for animating elements entering and leaving, <Transition> and <TransitionGroup>, which integrate with v-if, v-show, v-for, dynamic components and Vue Router. In this lesson you will learn the cycle of classes they apply, how to combine them with CSS transitions and animations, modes, custom classes, JavaScript hooks, animated lists with the FLIP technique, transitions between routes and two aspects that are often forgotten: accessibility (prefers-reduced-motion) and performance. In Colmena you will animate the new booking notice, the user menu, the bookings that leave the list, the catalogue cards when filtering and the move between screens, and you will create a reusable transition component, FadeTransition.
Contents
- How Vue animates entering and leaving
<Transition>and the cycle of classes- CSS transitions and
@keyframesanimations nameandappear- Modes:
out-inandin-out - Custom classes and CSS libraries
- Explicit duration
- JavaScript hooks
- A reusable transition component:
FadeTransition <TransitionGroup>: animated lists- Transitions between routes
- Accessibility:
prefers-reduced-motion - Performance: which properties to animate
- Try it
- How Vue animates entering and leaving
Animating an element that is already in the DOM is easy with CSS: you change a class and a transition does the rest. The problem is elements that enter or leave the DOM with v-if or v-for:
- To animate an entrance, the element first has to be inserted in its initial state (invisible, shifted) and, an instant later, move to its final state so that the CSS transition has something to animate.
- To animate an exit, the element has to stay in the DOM while it is animated, and be removed only when the animation finishes. But
v-ifwould remove it immediately.
<Transition> solves both: it adds and removes classes at exactly the right moment and delays removing the element until the transition finishes. It works with content that enters and leaves through:
| Mechanism | Example |
|---|---|
v-if / v-else |
The new booking notice |
v-show |
The user menu panel (the display is animated) |
Dynamic components <component :is> |
The catalogue's three views |
A change of key |
A text that changes and must be animated as if it were another element |
<RouterView> (with its slot) |
Moving from one screen to another |
And <TransitionGroup> does the same for each element of a list generated with v-for, as well as animating those that change position.
<Transition> and the cycle of classes
<Transition> and the cycle of classes<Transition> wraps a single element or component (which must have a single root node) and adds nothing to the DOM. When its content enters or leaves, it applies six classes:
| Class | When it is added | When it is removed | What it is for |
|---|---|---|---|
v-enter-from |
Before inserting the element | One frame after inserting it | The entrance's initial state |
v-enter-active |
Before inserting | When the transition finishes | Declaring the entrance's transition (duration, curve) |
v-enter-to |
One frame after inserting | When the transition finishes | The entrance's final state |
v-leave-from |
When the exit starts | One frame later | The exit's initial state |
v-leave-active |
When the exit starts | When it finishes (and then the element is removed) | Declaring the exit's transition |
v-leave-to |
One frame after the exit starts | When it finishes | The exit's final state |
sequenceDiagram
participant V as Vue
participant E as Element
Note over V,E: ENTER (v-if becomes true)
V->>E: enter-from + enter-active classes, and it is inserted
V->>E: next frame: removes enter-from, adds enter-to
Note over E: the CSS transition animates from "from" to "to"
E-->>V: transitionend
V->>E: removes enter-active and enter-to
Note over V,E: LEAVE (v-if becomes false)
V->>E: leave-from + leave-active classes (the element stays in the DOM)
V->>E: next frame: removes leave-from, adds leave-to
Note over E: the CSS transition animates towards "to"
E-->>V: transitionend
V->>E: removes the element from the DOM
The minimal example, a fade:
<script setup>
import { ref } from 'vue'
const visible = ref(true)
</script>
<template>
<button type="button" @click="visible = !visible">Toggle</button>
<Transition>
<p v-if="visible">Hello from Colmena</p>
</Transition>
</template>
<style>
.v-enter-active,
.v-leave-active {
transition: opacity 0.3s ease;
}
.v-enter-from,
.v-leave-to {
opacity: 0;
}
</style>Notice what you do not need to write: v-enter-to and v-leave-from. The element's "normal" state is already opacity: 1, so it is enough to say where it comes from (enter-from) and where it is going (leave-to). That is the usual approach.
How does Vue know when the transition finishes? It reads the duration of the transition (or the animation) in the element's computed styles and waits for the transitionend (or animationend) event. If the element has no CSS transition at all, entering and leaving are immediate.
- CSS transitions and
@keyframes animations
@keyframes animations<Transition>'s classes work equally well with CSS's two animation tools:
transition |
animation with @keyframes |
|
|---|---|---|
| What it animates | The change from one state to another, when a property changes | A sequence of keyframes defined separately |
| Intermediate steps | Only start and end | As many as you like (0%, 50%, 100%...) |
| Where the states go with Vue | enter-from / leave-to |
Inside @keyframes; enter-active / leave-active only declare the animation |
| Typical use | Fading, sliding, scaling | Bounces, shakes, effects with several phases |
An animation with keyframes, for example for an error notice that "grabs attention" when it appears:
.shake-enter-active {
animation: shake 0.4s ease;
}
.shake-leave-active {
animation: shake 0.2s ease reverse; /* the same animation, in reverse */
}
@keyframes shake {
0% { opacity: 0; transform: translateX(0); }
25% { opacity: 1; transform: translateX(-6px); }
50% { transform: translateX(6px); }
75% { transform: translateX(-3px); }
100% { transform: translateX(0); }
}With animations you do not need enter-from: the animation itself defines the initial state in its 0%.
name and appear
name and appear4.1 name: several different transitions
With a single set of v-* classes, every transition in the application would be the same. The name prop changes the prefix: <Transition name="fade"> uses fade-enter-from, fade-enter-active, etc. That way you can define several named transitions and choose which one to use in each place:
<Transition name="fade">...</Transition> <!-- .fade-enter-from, ... -->
<Transition name="slide">...</Transition> <!-- .slide-enter-from, ... -->
<Transition :name="transitionType">...</Transition> <!-- dynamic -->4.2 appear: animating the first appearance too
By default, <Transition> does not animate content that is already present when it mounts: only subsequent changes. With the appear prop, the first render is animated with the enter classes too.
In Colmena this matters for the new booking notice in "My bookings" (04-05): when BookingView creates the booking and navigates to /dashboard/bookings?new=..., the view mounts with the notice already visible. Without appear, it would pop up all at once; with appear, it slides in. We will apply it in section 9.
- Modes:
out-in and in-out
out-in and in-outWhen <Transition> swaps one element for another (a v-if/v-else, a dynamic component, a change of key), by default the old one leaving and the new one entering happen at the same time. For an instant both are in the DOM, one on top of the other or one below the other, which usually looks like a jump. The mode prop controls this:
| Mode | What happens | When to use it |
|---|---|---|
| (no mode) | Leaving and entering at the same time | Overlapping elements with position: absolute (a cross-fade) |
out-in |
The old one leaves first; when it has finished, the new one enters | The usual case: changing texts, screens, tabs |
in-out |
The new one enters first; when it has finished, the old one leaves | Rare; effects in which the new one covers the old one |
A small example in Colmena: the "Copy link to this search" button in RoomsView (04-05) changes its text to "Link copied" for two seconds. With a transition, the change is easier to notice:
<!-- RoomsView.vue: the text of the copy button -->
<BaseButton variant="secondary" @click="copyLink">
<Transition name="fade" mode="out-in">
<span :key="linkCopied">
{{ linkCopied ? 'Link copied' : 'Copy link to this search' }}
</span>
</Transition>
</BaseButton>:key="linkCopied"is what turns a change of text into an entrance and an exit: when the key changes, Vue considers it to be another<span>, and<Transition>animates the old one leaving and the new one entering. Without thekey, Vue would reuse the same<span>and only change its text, without any animation.mode="out-in"stops the button from containing both texts for an instant.name="fade"is the transition we will define globally in section 9.
- Custom classes and CSS libraries
If you use a CSS animation library, such as Animate.css, its classes have their own names (animate__animated animate__fadeInDown) that do not follow Vue's pattern. The enter-from-class, enter-active-class, enter-to-class, leave-from-class, leave-active-class and leave-to-class props replace the corresponding class:
<!-- With Animate.css installed (we do not add it to Colmena) -->
<Transition
enter-active-class="animate__animated animate__fadeInDown"
leave-active-class="animate__animated animate__fadeOutUp"
>
<p v-if="visible" class="notice">Room booked</p>
</Transition>They are also useful for integrating transitions with CSS utilities (for example, Tailwind CSS's: enter-from-class="opacity-0 -translate-y-2"), where the classes cannot carry Vue's prefix.
- Explicit duration
Vue deduces the transition's duration from the styles of the root element that enters or leaves. This fails in two cases:
- Nested transitions: the root element fades out in 0.2 s, but a child has a longer transition, with a delay. Vue would finish the exit after 0.2 s and remove the child halfway through its animation.
- Durations that cannot be read, because the animation is done by a library or applied indirectly.
The duration prop sets the duration in milliseconds:
<Transition name="panel" :duration="400">...</Transition>
<Transition name="panel" :duration="{ enter: 500, leave: 250 }">...</Transition>Use it only when automatic detection does not work: if the duration is in both the CSS and the prop, you will have to keep the two in sync.
- JavaScript hooks
<Transition> emits events at each phase, which let you animate with JavaScript instead of (or as well as) CSS classes:
| Event | Moment | Arguments |
|---|---|---|
@before-enter |
Before inserting | (el) |
@enter |
On inserting: the animation starts here | (el, done) |
@after-enter |
When the entrance finishes | (el) |
@enter-cancelled |
If the entrance is interrupted (the element leaves before it has finished entering) | (el) |
@before-leave, @leave, @after-leave, @leave-cancelled |
The same for the exit | (el) / (el, done) |
The done argument is the key: in @enter and @leave, Vue waits for you to call it before considering the phase finished. If you animate with JavaScript and do not call it, the entrance never finishes and the exit never removes the element. When the animation is JavaScript only, add :css="false": Vue will not look for CSS transitions (it will not wait for transitionend events) and will rely on done.
8.1 A case CSS does not handle well: height
CSS cannot animate height: auto. For a block to expand smoothly from height 0 to its natural height, you have to measure it, and that means JavaScript. Colmena's shortcuts help (ShortcutsHelp, with its v-show="showHelp" block from 02-07) is a good candidate. The browser's Web Animations API (element.animate) is enough, without libraries:
<!-- ShortcutsHelp.vue: wrap the block that is shown with v-show -->
<Transition :css="false" @enter="expand" @leave="collapse">
<div v-show="showHelp" class="help">
<!-- content, unchanged -->
</div>
</Transition>// ShortcutsHelp.vue
const DURATION_MS = 200
function expand(el, done) {
const height = el.scrollHeight // the content's natural height
const animation = el.animate(
[{ height: '0px', opacity: 0 }, { height: `${height}px`, opacity: 1 }],
{ duration: DURATION_MS, easing: 'ease-out' }
)
animation.onfinish = done
animation.oncancel = done
}
function collapse(el, done) {
const animation = el.animate(
[{ height: `${el.scrollHeight}px`, opacity: 1 }, { height: '0px', opacity: 0 }],
{ duration: DURATION_MS, easing: 'ease-in' }
)
animation.onfinish = done
animation.oncancel = done
}/* ShortcutsHelp.vue: so that the content does not spill out while the height grows */
.help {
overflow: hidden;
}el.scrollHeightis the height the content would have without constraints. On entering, the element is already in the DOM (Vue has inserted it or removed itsdisplay: none), so it can be measured.el.animatereturns anAnimationobject; itsonfinishcallsdone.oncancelcovers the case where the animation is interrupted.- When it finishes, the animation disappears and the element returns to its natural height (
auto), so if the content changes afterwards, it adapts. - Animating
heighthas a performance cost (section 13), which is acceptable for a small block that expands at the user's request.
8.2 Animation libraries
For complex animations (sequences, physics, animations chained to page scrolling), JavaScript hooks let you use any library. With GSAP, for example, the enter hook would look like this:
// With GSAP installed (we do not add it to Colmena)
import { gsap } from 'gsap'
function expand(el, done) {
gsap.from(el, { height: 0, opacity: 0, duration: 0.2, onComplete: done })
}The pattern is always the same: the library animates, and when it finishes, you call done.
- A reusable transition component:
FadeTransition
FadeTransitionIf each component defines its own transition classes, the application ends up with a dozen slightly different fades. The solution is a transition component: a component that wraps <Transition> with its configuration and its styles, and is used just like it.
Create src/components/base/FadeTransition.vue:
<script setup>
// src/components/base/FadeTransition.vue
// Colmena's standard fade; with "slide", it also moves slightly.
const { slide = false } = defineProps({
slide: Boolean
})
</script>
<template>
<Transition :name="slide ? 'slide' : 'fade'">
<slot />
</Transition>
</template>
<style>
/* Not "scoped": these classes are applied to the slot's content, which belongs to the parent */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.slide-enter-active,
.slide-leave-active {
transition: opacity 0.25s ease, transform 0.25s ease;
}
.slide-enter-from,
.slide-leave-to {
opacity: 0;
transform: translateY(-0.5rem);
}
</style>Three important details:
<style>withoutscoped: the element being animated is the slot's content, which belongs to the parent component. Withscoped, the rules would only apply toFadeTransition's own elements, and there are none. That is why the class names must be specific enough not to clash with anything (fade-*,slide-*).<Transition>'s other props arrive by themselves.FadeTransition's root node is the<Transition>, so attributes that are not props of the component (appear,mode,@after-enter...) fall through (03-05) and end up on it.<FadeTransition appear mode="out-in">works without writing anything else.- The styles are loaded with the component: as soon as some component imports it, the
fade-*classes exist on the page. That is why the copy button in section 5 can usename="fade"directly, although it would be more consistent for it to use the component too.
9.1 The new booking notice
In src/views/dashboard/DashboardBookingsView.vue, wrap the notice:
<!-- DashboardBookingsView.vue -->
<FadeTransition slide appear>
<div v-if="newBooking" class="note new-booking-notice" role="status" data-test="new-booking-notice">
<!-- the notice's content and "Close" button, unchanged -->
</div>
</FadeTransition>On arriving from the form, the notice slides down (appear); when "Close" is clicked, closeNotice removes ?new from the URL, newBooking becomes undefined and the notice fades upwards before being removed.
9.2 The user menu
The user menu panel in AppHeader (06-02) uses v-show. We will give it its own transition, which makes it grow from the corner of the button:
<!-- AppHeader.vue: wrap only the panel, not the container with v-click-outside -->
<Transition name="menu">
<div v-show="menuOpen" id="user-menu" class="user-menu__panel">
<!-- content, unchanged -->
</div>
</Transition>/* AppHeader.vue, in the <style scoped> */
.user-menu__panel {
/* ...the rules it already had, plus: */
transform-origin: top right; /* grows from the corner of the button */
}
.menu-enter-active,
.menu-leave-active {
transition: opacity 0.15s ease, transform 0.15s ease;
}
.menu-enter-from,
.menu-leave-to {
opacity: 0;
transform: scale(0.95) translateY(-0.25rem);
}- Here
scopeddoes work, unlike inFadeTransition: the panel is an element ofAppHeader's own template, so it carries itsdata-v-...attribute. - With
v-show, the transition animates the change fromdisplay: noneto visible and back. The panel always exists in the DOM, soaria-controls="user-menu"still points to a real element, which is why we chosev-showin 06-02. - The
v-click-outsidedirective does not change: it stays on the container, which is not animated.
<TransitionGroup>: animated lists
<TransitionGroup>: animated lists10.1 How it works
<TransitionGroup> animates the elements of a list generated with v-for. It differs from <Transition> on four points:
<Transition> |
<TransitionGroup> |
|
|---|---|---|
| Content | A single element | Several elements (normally a v-for) |
| Element in the DOM | None | None, unless you specify tag="ul" (or whichever) |
key |
Only to force the element to change | Required on every child |
| Classes | -enter-*, -leave-* |
The same, per element, plus -move for those that change position |
| Modes | out-in, in-out |
They do not exist |
The -move class is what makes <TransitionGroup> special. When an element enters or leaves, the others change position. If you did nothing, they would jump to their new place; with a rule for -move, they glide smoothly. Vue achieves this with the FLIP technique:
flowchart LR
F["First<br/>Before updating,<br/>measure each element's position"] --> L["Last<br/>Update the DOM<br/>and measure the new position"]
L --> I["Invert<br/>Apply a transform that returns<br/>each element to its old position"]
I --> P["Play<br/>Add the -move class and remove the transform:<br/>the transition takes it to its place"]
The trick is that the browser only animates transform, which is cheap (section 13): the element is already in its new position in the document flow, and what you see gliding is a visual offset shrinking to zero.
10.2 The bookings that leave the list
In "My bookings", with the "Hide cancelled bookings" checkbox from 06-01 ticked, a booking that is cancelled disappears from the list. Today it does so abruptly and the following ones jump up. In DashboardBookingsView.vue, replace the <ul v-else class="booking-list"> tag (and its closing tag) with a <TransitionGroup>:
<!-- DashboardBookingsView.vue -->
<TransitionGroup v-else tag="ul" name="booking" class="booking-list">
<li
v-for="booking in visibleBookings"
:key="booking.id"
v-memo="[booking.status, isCancelling(booking.id), booking.id === newBookingId, roomNameById(booking.roomId), locale]"
:class="{ 'booking-list__new': booking.id === newBookingId }"
:data-id="booking.id"
data-test="booking"
>
<!-- the row's content, unchanged -->
</li>
</TransitionGroup>/* DashboardBookingsView.vue, in the <style scoped> */
.booking-list {
position: relative; /* reference for the rows that leave */
}
.booking-enter-active,
.booking-leave-active,
.booking-move {
transition: opacity 0.3s ease, transform 0.3s ease;
}
.booking-enter-from,
.booking-leave-to {
opacity: 0;
transform: translateX(1.5rem);
}
/* The leaving row stops taking up space: the others can move at the same time */
.booking-leave-active {
position: absolute;
left: 0;
right: 0;
}Let's analyse the pieces:
tag="ul"makes<TransitionGroup>render the<ul>. Thebooking-listclass and any other attribute fall through to that<ul>, so the styles and tests that looked for it keep working.v-elseworks on<TransitionGroup>just as it did on the<ul>: it is one more component in the chain of conditions..booking-movereceives the same transition: it is the one that animates the rows moving up when another disappears.position: absoluteon leaving: while the cancelled row fades out, if it kept occupying its slot, the others could not start moving up until it finished. By taking it out of the flow, the others move at the same time as it fades.left: 0; right: 0preserves its width, and the<ul>'sposition: relativeis the reference for positioning it.- Compatible with the existing
v-memo.<TransitionGroup>adds its transition hooks to each virtual node on every render, including those thatv-memoreuses from the cache, and it only needs what we already had: a stablekeyper row. Thev-memodependencies do not change, because the transition does not alter what the row shows. If a memoised row ever fails to animate, check that thekeyis on the same element as thev-forand thev-memo.
With the checkbox unticked, cancelling does not remove the row (its badge changes to "Cancelled"), so there is nothing to animate; but when you tick the checkbox, all the cancelled bookings leave at once and the others rearrange themselves. And if the cancellation fails and is rolled back (05-07), the row comes back in with the enter animation.
A warning for large lists. To animate the moves,
<TransitionGroup>measures the position of all its elements before and after each update. With dozens of rows it is imperceptible; with the 3,000 bookings from the test in 06-01, every change forces the browser to calculate thousands of positions. We will measure it and solve it in Performance Optimization.
10.3 The catalogue cards when filtering
In the catalogue, when a filter changes (capacity, equipment, search), the cards that no longer match disappear and the others rearrange themselves in the grid. It is the classic <TransitionGroup> case. The list is in src/components/RoomList.vue (03-04), which renders a <ul class="room-list"> with a RoomCard (or the #room slot) for each room:
<!-- RoomList.vue: replace <ul class="room-list"> and its closing tag -->
<TransitionGroup tag="ul" name="card" class="room-list">
<li v-for="room in rooms" :key="room.id">
<!-- #room slot with RoomCard by default, unchanged -->
</li>
</TransitionGroup>/* RoomList.vue, in the <style scoped> */
.card-move,
.card-enter-active,
.card-leave-active {
transition: opacity 0.3s ease, transform 0.3s ease;
}
.card-enter-from,
.card-leave-to {
opacity: 0;
transform: scale(0.9);
}
.card-leave-active {
position: absolute;
}- It works with CSS grid: FLIP measures real on-screen positions, so it does not matter how they are calculated (normal flow, flexbox or grid).
position: absolutewithoutleft/right: the leaving card keeps the width it had becauseRoomCarddefines it on its own container. If it shrinks on leaving, give it an explicit width.- When changing floor, on the other hand, there is no animation: since 05-06, changing floor makes no request, but the floor's catalogue is replaced as a whole and most of the cards leave and enter at the same time. That is the expected behaviour.
- Sorting by price is animated too: the cards neither enter nor leave, they only change position, and the
-moveclass glides them to their new place. It is FLIP's most striking effect.
- Transitions between routes
11.1 <RouterView> with its slot
<RouterView> exposes the current route's component in its slot, which lets you wrap it in a transition:
<RouterView v-slot="{ Component, route }">
<Transition name="fade" mode="out-in">
<component :is="Component" :key="route.path" />
</Transition>
</RouterView>Componentis the component the router would render;route, the current route.<component :is>renders it inside the transition.mode="out-in": the previous screen leaves first and the new one enters afterwards, so that they never coexist.
Before applying it to Colmena, there are two problems to solve.
First: the key. With :key="route.path", every change of address counts as a new screen: navigating from /rooms/polen to /rooms/nectar would unmount and remount RoomDetailView, when in 04-03 we decided to reuse it; and going from "Profile" to "Bookings" inside /dashboard would unmount DashboardView with its side menu, which the nested routes (04-04) keep fixed. The right key is the top-level record: route.matched[0]?.path is /rooms/:id(...) for any spec sheet and /dashboard for any dashboard sub-screen.
Second: a single root node. <Transition> can only animate a component whose content is a single element. Several of Colmena's views have several root nodes: RoomsView starts with <ShortcutsHelp />, continues with the catalogue section and ends with the room panel; DashboardBookingsView has a title, notices, the checkbox and the list. Vue would warn in the console ("Component inside <div> in App.vue.
11.2 In Colmena
In src/App.vue, replace <main class="content"><RouterView /></main>:
<!-- App.vue -->
<main class="content">
<RouterView v-slot="{ Component, route }">
<Transition :name="route.meta.transition ?? 'page'" mode="out-in">
<div :key="route.matched[0]?.path" class="view">
<component :is="Component" />
</div>
</Transition>
</RouterView>
</main>/* App.vue, in the <style scoped> */
.page-enter-active,
.page-leave-active {
transition: opacity 0.15s ease;
}
.page-enter-from,
.page-leave-to {
opacity: 0;
}
.forward-enter-active,
.forward-leave-active {
transition: opacity 0.15s ease, transform 0.15s ease;
}
.forward-enter-from {
opacity: 0;
transform: translateX(1.5rem);
}
.forward-leave-to {
opacity: 0;
transform: translateX(-1.5rem);
}And in src/router/index.js, the meta.transition field that we already typed in 09-02, on the routes that "move forward" to a detail:
// src/router/index.js
{
path: '/rooms/:id([a-z-]+)',
name: 'room-detail',
// ...
meta: { title: 'Room details', transition: 'forward' }
},
{
path: '/book/:roomId([a-z-]+)',
name: 'book',
// ...
meta: { title: 'New booking', requiresSession: true, transition: 'forward' }
},- The
<div class="view">belongs toApp's template, so it carries thescopedattribute and the transition classes can be defined inApp.vue's<style scoped>. It is the only element that is animated, whether the view has one root node or several. :key="route.matched[0]?.path": the transition is only triggered when the top-level section changes. Going from one spec sheet to another or from one dashboard tab to another does not trigger it, and the components are reused as before.route.meta.transition ?? 'page': each route can ask for its transition; if it says nothing, a fade. Since the name is evaluated with the destination route, the screen that leaves and the one that enters use the same transition: when going from the catalogue to a spec sheet, the catalogue leaves to the left and the spec sheet enters from the right.- Short durations (0.15 s): with
out-in, the user waits for the exit and the entrance. A transition between screens that is too noticeable becomes a nuisance.
11.3 Scrolling and the transition
The router's scrollBehavior (04-02) takes the page to the top as soon as the navigation is confirmed, that is, while the previous screen is still fading out: the user sees the old page jump. scrollBehavior can return a promise, so all you need to do is wait for the exit to finish:
// src/router/index.js
const EXIT_DURATION_MS = 150 // that of .page-leave-active / .forward-leave-active
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
scrollBehavior(to, from, savedPosition) {
const destination = savedPosition ?? (to.hash ? { el: to.hash, top: 16, behavior: 'smooth' } : { top: 0 })
// If the section changes (there is a transition), wait for the previous screen to leave
if (to.matched[0]?.path === from.matched[0]?.path) return destination
return new Promise((resolve) => setTimeout(() => resolve(destination), EXIT_DURATION_MS))
}
})The destination logic is the usual one; what is new is the wait, only when the transition's key changes.
- Accessibility:
prefers-reduced-motion
prefers-reduced-motionFor some people, animations are not an embellishment but a problem: vestibular disorders can cause dizziness or nausea with on-screen movement, and animations distract people with attention difficulties. Operating systems have an option to reduce motion, and the browser exposes it with the prefers-reduced-motion media query.
The rule is not to remove all animation, but to remove movement (shifts, scaling, bounces) and keep, if you wish, the gentle opacity changes, which help people understand what has changed without moving anything. In src/assets/main.css:
/* src/assets/main.css: at the end */
@media (prefers-reduced-motion: reduce) {
/* No shifting or scaling: only opacity changes, very brief */
.slide-enter-from,
.slide-leave-to,
.forward-enter-from,
.forward-leave-to,
.booking-enter-from,
.booking-leave-to,
.card-enter-from,
.card-leave-to,
.menu-enter-from,
.menu-leave-to {
transform: none !important;
}
/* The list movements, disabled */
.booking-move,
.card-move {
transition: none !important;
}
}!importantis necessary because the original rules are in scoped styles, whose selector (.booking-enter-from[data-v-...]) is more specific than that of a global stylesheet.- JavaScript animations are not affected by the CSS. In
ShortcutsHelp, check the preference before animating:
// ShortcutsHelp.vue
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)')
function expand(el, done) {
if (reducedMotion.matches) return done() // no height animation
// ... the animation from before
}VueUse offers the same check as a reactive composable: usePreferredReducedMotion() returns a ref whose value is 'reduce' or 'no-preference' and which changes if the user changes the option while the application is open.
- Performance: which properties to animate
To display each frame, the browser goes through a series of phases: calculating styles, layout (the size and position of each box), painting (filling in pixels) and compositing (combining layers). Animating a property forces the browser to repeat, on every frame, the phase that property affects and all the following ones:
| Animated property | Phases repeated on every frame | Cost |
|---|---|---|
transform, opacity |
Compositing only (normally on the GPU) | Low: the recommended choice |
color, background-color, box-shadow |
Painting and compositing | Medium |
width, height, top, left, margin, padding |
Layout, painting and compositing, and often of neighbouring elements too | High |
That is why all the transitions in this lesson use opacity and transform (translate, scale), and why FLIP turns a change of position into a transform. The deliberate exception is ShortcutsHelp's height, acceptable because it is a small block animated on request.
Other tips:
- Short durations: between 150 and 300 ms for most interface transitions. Longer ones make the application feel slow, however pretty they may be.
will-change: transformtells the browser that an element is going to be animated so that it prepares it on its own layer. Use it sparingly and only if you measure a problem: each layer consumes memory.- Measure with the Performance tab of the browser's developer tools (you will look at it in depth in 09-07): frames that take longer than 16 ms are flagged.
13.1 And the tests
- Vue Test Utils replaces
<Transition>and<TransitionGroup>by default with versions that do not animate: theDashboardBookingsViewunit tests keep working exactly the same, without any waiting. If you ever need to test the real transition, those stubs are disabled withglobal: { stubs: { transition: false, 'transition-group': false } }. - Cypress retries its assertions until they pass (for up to 4 seconds by default): if a row takes 300 ms to disappear,
should('not.exist')simply waits. The tests from 08-04 stay green without any changes.
- Try it
- The cycle of classes. In the catalogue, open the element inspector on the list of cards and type a search that hides several of them: you will see
card-leave-activeandcard-leave-toappear and disappear on those leaving. To watch it calmly, slow the speed down to 10% in the Animations tab of Chrome's developer tools. - FLIP. Change the sort order to "Cheapest first" and then to "Most expensive first": the cards glide to their new positions. Temporarily remove the
.card-moveclass from the CSS and repeat: they jump. Restore it. - Notice and
out-inmode. Create a booking: the notice slides in on arriving at "My bookings". Close it: it fades out. In the catalogue, click "Copy link to this search": the text changes with a fade, without the two being seen at the same time. Removemode="out-in"and repeat to see the difference. - Bookings that leave. With "Hide cancelled bookings" ticked, cancel a booking: the row fades out to the right and the following ones move up at the same time. Set
ERROR_PROBABILITY = 1in the simulation and cancel another: the row leaves and, when the API fails, comes back in. Restore the value. - Menu. Open and close the user menu with the mouse and with Escape: it grows from the corner of the button and fades when it closes.
- Screens. Navigate from the catalogue to a spec sheet: the spec sheet enters from the right. From the spec sheet, click another room under "Other rooms": there is no transition (the view is reused). In the dashboard, go from "Profile" to "My bookings": the side menu does not move. Scroll down in the catalogue and open a spec sheet: the page does not jump before fading out.
- Reduced motion. In Chrome's developer tools, open Rendering (from the command menu, "Show Rendering") and emulate
prefers-reduced-motion: reduce. Repeat steps 2, 4 and 6: the changes are brief fades, without any movement, and the shortcuts help expands without animation. - The tests.
npm testandnpm run test:e2estay green.
Common Mistakes and Tips
- Putting several elements, or a component with several root nodes, inside
<Transition>. It is not animated and Vue warns in the console. A single element; for lists,<TransitionGroup>. - Changing the content without changing the
key. If the element is the same and only its text changes, there is no entrance or exit. Use:keyso that Vue treats it as another element. - Forgetting the
keys in<TransitionGroup>. They are required: without them, Vue cannot know which element is entering, leaving or moving. - Using
<style scoped>in a reusable transition component. The classes do not reach the slot's content. Use global styles with specific names. - Not calling
donein the@enterand@leavehooks of a JavaScript animation. The entrance never finishes and the exit never removes the element. - Using
:key="route.path"in the route transition without thinking about it. It unmounts views that were designed to be reused (route params, nested routes). Choose the key according to which change should be animated. - Animating
width,height,toporlefton large elements or in lists. It triggers layout recalculations on every frame. Animatetransformandopacity. - Ignoring
prefers-reduced-motion. It is a user preference, like the language. Remove movement when they ask for it. - Tip: every animation should answer a question: what does it help the user understand? If it does not help them understand anything, it is probably superfluous.
Exercises
Exercise 1. The loading indicator of lazy views, the replacement of "Loading the room…" with the spec sheet in RoomDetailView, appears and disappears abruptly. Use FadeTransition with mode="out-in" so that going from "loading" to "spec sheet" (and to "error") is a fade. Hint: the v-if/v-else-if chain must be inside the transition, and each branch must be a single element.
Exercise 2. Instead of declaring transition: 'forward' route by route, make the direction depend on the depth: if the destination route has more segments than the origin one (/rooms → /rooms/nectar), the transition is forward; if it has fewer, back (the same animation in the opposite direction); if it has the same number, page. Calculate it in an afterEach and store it in to.meta.transition. Also write the CSS for back.
Exercise 3. Create a TimedNotice component that shows a message (the message prop) and hides it by itself after five seconds, with a progress bar that empties over that time. The entrance and exit must use FadeTransition with slide, and the bar must be animated with CSS only (@keyframes with transform: scaleX). Use it for the cancellation error message in DashboardBookingsView.
Solutions
Solution 1. In RoomDetailView.vue, wrap the chain of states (not NotFoundView, which replaces the whole view):
<FadeTransition mode="out-in">
<p v-if="loading" key="loading">Loading the room…</p>
<div v-else-if="error" key="error" class="notice" role="alert">
<!-- message and Retry button, unchanged -->
</div>
<BasePanel v-else-if="room" key="sheet">
<!-- spec sheet, unchanged -->
</BasePanel>
</FadeTransition>A v-if/v-else-if chain counts as a single child for <Transition>, because at any moment there is only one branch. The different keys are not strictly necessary (Vue tells the branches apart), but they make it explicit that they are different elements. BasePanel must have a single root node, which it does. Note: if room changes from one room to another (navigating between spec sheets), the branch is still the same and there is no fade, which is what we want.
Solution 2.
// src/router/index.js, after the title afterEach
router.afterEach((to, from) => {
const depth = (route) => route.path.split('/').filter(Boolean).length
const destination = depth(to)
const origin = depth(from)
to.meta.transition = destination > origin ? 'forward' : destination < origin ? 'back' : 'page'
})/* App.vue */
.back-enter-active,
.back-leave-active {
transition: opacity 0.15s ease, transform 0.15s ease;
}
.back-enter-from {
opacity: 0;
transform: translateX(-1.5rem);
}
.back-leave-to {
opacity: 0;
transform: translateX(1.5rem);
}Remove the transition: 'forward' entries from the routes: the afterEach calculates them. It works because afterEach runs before <RouterView> re-renders, so route.meta.transition already has the new value when App.vue's template reads it. Bear in mind that to.meta is the route record's meta object, shared by every navigation to that route: writing to it is acceptable for a value that is recalculated on every navigation, like this one, but do not use it to store state.
Solution 3.
<!-- src/components/TimedNotice.vue -->
<script setup>
import { ref, watch, onScopeDispose } from 'vue'
import FadeTransition from '@/components/base/FadeTransition.vue'
const DURATION_MS = 5000
const { message } = defineProps({ message: { type: String, default: '' } })
const visible = ref(false)
let timer = null
watch(
() => message,
(text) => {
clearTimeout(timer)
visible.value = Boolean(text)
if (text) timer = setTimeout(() => (visible.value = false), DURATION_MS)
},
{ immediate: true }
)
onScopeDispose(() => clearTimeout(timer))
</script>
<template>
<FadeTransition slide>
<div v-if="visible" :key="message" class="notice timed-notice" role="alert">
<p>{{ message }}</p>
<div class="timed-notice__bar" :style="{ animationDuration: `${DURATION_MS}ms` }"></div>
</div>
</FadeTransition>
</template>
<style scoped>
.timed-notice__bar {
height: 3px;
background: currentColor;
transform-origin: left;
animation: drain linear forwards;
}
@keyframes drain {
from { transform: scaleX(1); }
to { transform: scaleX(0); }
}
@media (prefers-reduced-motion: reduce) {
.timed-notice__bar {
animation: none;
}
}
</style>In DashboardBookingsView, replace the cancellation error paragraph with <TimedNotice :message="cancellationErrorText" />, with a cancellationErrorText computed that builds the translated text from cancellationError (or '' if there is no error). The key with the message means that a new error restarts the bar. scaleX animates only transform, so it is cheap; with width it would work just the same, but with the cost shown in the table in section 13.
Conclusion
<Transition> animates a single element entering and leaving (with v-if, v-show, dynamic components or changes of key) by applying the cycle of classes -enter-from, -enter-active, -enter-to and their -leave-* equivalents, and by delaying the element's removal until the CSS transition or animation finishes. With name you choose the set of classes, with appear you animate the first render, with mode="out-in" you prevent the leaving and entering elements from coexisting, with custom classes you integrate CSS libraries, with duration you set the duration when it cannot be deduced, and with JavaScript hooks (and their done) you animate with the Web Animations API or with libraries such as GSAP. <TransitionGroup> brings all of this to lists, with the -move class and the FLIP technique for elements that change position. Colmena now has FadeTransition as its standard transition, a new booking notice that slides in, a user menu that grows from its button, bookings and cards that leave and rearrange themselves smoothly (compatible with the existing v-memo) and transitions between screens guided by meta.transition, all while respecting prefers-reduced-motion and animating only transform and opacity.
There is one piece of interface that does not yet have its animation because it does not exist yet: the modal dialog. Colmena still asks "Cancel the booking?" with the browser's window.confirm, which cannot be styled our way, animated or tested comfortably. Building a modal of our own requires it to be rendered above everything else, outside the component hierarchy, and that is the first of the topics in Teleport, Suspense and Error Handling.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
