Blog>
Snippets

Animating Routes with Vue Router

Demonstrate how to animate route transitions for a single-page application with Vue Router and the <Transition> component, providing a smoother user experience.
/* main.js - Setup Vue with Vue Router */
import Vue from 'vue';
import Router from 'vue-router';
import App from './App.vue';
import HomeComponent from './components/Home.vue';
import AboutComponent from './components/About.vue';

// Tell Vue to use the router
Vue.use(Router);

const router = new Router({
  mode: 'history',
  routes: [
    { path: '/', component: HomeComponent },
    { path: '/about', component: AboutComponent }
  ]
});

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');
This code sets up Vue with Vue Router, initializing the routes and mounting the main App component to the '#app' element in the index.html.
/* App.vue */
<template>
  <div id="app">
    <transition name="fade" mode="out-in">
      <router-view></router-view>
    </transition>
  </div>
</template>

<script>
export default {
  // Additional component options if necessary
};
</script>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
  opacity: 0;
}
</style>
This code snippet is the content of the App.vue component, which includes a <transition> wrapper around the <router-view>. It specifies a 'fade' animation for the route components as they enter and leave, with a half-second duration for the opacity transition.