Blog>
Snippets

Animating Route Transitions in Vue.js 3 SPA

Adding animations to route transitions in a Vue.js 3 application to provide visual feedback and a smoother user experience when navigating.
<template>
  <router-view v-slot="{ Component }">
    <transition name="fade" mode="out-in">
      <!-- we render the router component here -->
      <component :is="Component" />
    </transition>
  </router-view>
</template>
This template code defines a transition effect for routing components with the name 'fade'. When route changes, the current page fades out before the new page fades in, because of the 'out-in' mode.
<script>
import { defineComponent } from 'vue';

export default defineComponent({
  // Component logic here
});
</script>
Standard script block of a Vue single-file component, you can put your component's logic here.
<style>
/* Define enter and leave animations */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
This style tag contains CSS for the fade animation. '.fade-enter-active' and '.fade-leave-active' define the duration of the transition effect. '.fade-enter-from' and '.fade-leave-to' define the initial and final opacity states for the animation.