Page transition with fade effect using vue-router in Vue.js

Vue.js has variety of ways to apply effects on pages, such as transition effects. Vue provides transition wraper component which helps to add entering/leaving transitions for elements or components in the contexts such as conditional rendering, conditional display, dynamic components, component root nodes. Now lets go straight into using vue-router for page transition with fade effect. Add the styles for fade transition and wrap<router-view></router-view> with transition name=”fade”></transition>

Create your application using vue-cli


vue init webpack fadetransition

cd fadetransition

npm install

Install the router


npm i vue-router


If you are not using vue-cli add the vue-router as shown below:


<script src="/path/to/vue.js"></script>

<script src="/path/to/vue-router.js"></script>

step 1

To create page components. Components can be nested in Vue.js. If a page in the app is made with regular Vue component it is considered as root to other components. Create pages in src folder. The page root components will be put in this directory. Other components used in the actual pages will be put in ready-made components directory. In src/pages create two files page1 and page2.

<template>

<h1>Page 1</h1>

</template>


<script>

export default {

}

</script>


<style scoped>

</style>

step 2.

To setup routing edit the generated src/main.js and add required imports.

import VueRouter from 'vue-router'

import Page1 from './pages/Page1'

import Page2 from './pages/Page2'

Now add global router usage.


Vue.use(VueRouter)


Then add router setup.


const router = new VueRouter({
  routes: [
    { path: '/page1', component: Page1 },
    { path: '/page2', component: Page2 },
    { path: '/', redirect: '/page1' }
  ]
})


Edit app initiation


new Vue({

router,

el: '#app',

render: h =>h(App)

})

Step 3

Step 3 is to add a router view. The place where the page components will be rendered according to the route is missing and it is done by adding <router-view></router-view> in the templates, put it in the src/App.vue’s <template> tag.

Step 4

Now we reached the main part, adding transition effect between page components. As explained above wrap <router-view></router-view> with <transition name=”fade”></transition> element. Vue will create and insert appropriate CSS classes starting with the name specified throughout the effect’s duration. Define the effects in App.vue’s section.

<style>

.fade-enter-active, .fade-leave-active {

transition-property: opacity;

transition-duration: .25s;

}


.fade-enter-active {

transition-delay: .25s;

}


.fade-enter, .fade-leave-active {

opacity: 0

}

</style>