Vue Route Animations: Animating Page Changes
Animate between pages by wrapping your router view in a `<transition>` component, giving your SPA the feel of a native app. This is used for sliding or fading effects during navigation.
WHY IT EXISTS Single-page applications (SPAs) can feel jarring when content instantly swaps on navigation. Route transition animations solve this by adding motion, guiding the user's eye and creating a smoother, more polished experience similar to native mobile apps.
THE MENTAL MODEL Think of your <RouterView> as a stage. When a new route is triggered, the old component exits and the new one enters. By wrapping the component in Vue's <transition> element, you're telling Vue to apply CSS classes during this "scene change," allowing you to animate the process with fades, slides, or other effects.
HOW IT WORKS You use the v-slot directive on <RouterView> to get access to the Component being rendered. You then wrap this dynamic <component :is="Component"> inside a <transition> tag. To enable different animations for different routes, you can also access the route object in the slot. This allows you to dynamically set the transition's name based on route metadata, like :name="route.meta.transition". For example, you can create directional slide animations based on navigation depth by calculating it in an afterEach navigation guard and setting the meta field.
WHEN TO USE IT Use this to create a consistent look and feel across your application. It's ideal for simple fades between all pages or for more complex directional animations in hierarchical UIs, like sliding into a settings page and sliding back out. It significantly improves the perceived performance and user experience.
WHEN NOT TO USE IT Avoid overly complex or long animations that can frustrate users and make the app feel slow. A common footgun is that transitions fire on the initial page load because Vue Router's first navigation is asynchronous. To prevent an unwanted entry animation, you can await router.isReady() before mounting your app. Also, be mindful of performance on low-powered devices.
ONE CANONICAL EXAMPLE To apply a different transition for each route, define it in the route's meta field. Then, in your template, dynamically bind the transition name. First, define the routes: const routes = [{ path: '/home', component: Home, meta: { transition: 'fade' } }, { path: '/about', component: About, meta: { transition: 'slide-left' } }];. Then, the template uses this metadata: <router-view v-slot="{ Component, route }"> <transition :name="route.meta.transition || 'fade'"> <component :is="Component" :key="route.path" /> </transition> </router-view>. The :key attribute here forces the transition to run even if Vue tries to reuse the component instance.
Read the original → router.vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.