DEV Community

Pooya Goodarzi
Pooya Goodarzi

Posted on

How To Do Page Transitions In Vue.js

Hi there my fellow programmers.
Today we are here to see how we can have smooth page transitions in our SPA Vue.js app .
At first it may seem it's a huge deal and a lot of work to do . Well I'm here to tell you it's not
In fact it's really easy to have custom transitions while you are using vue-routerto change routes in your app.


There are several ways to apply transitions to routes but I'm gonna keep it short and tell the easiest way of all.

What tools do we need to add page transitions?
On top of your vueand vue-router you are going to need a small animation library designed for vue called vue-transify.
Note : This library support vue3 not vue 2.

Installation
Install the library via npm

npm install vue-transify

Add the css styles to your main.js

import { createApp } from 'vue'
import App from './App.vue'
import "vue-transify/dist/vue-transify.css";

createApp(App).mount('#app')
Enter fullscreen mode Exit fullscreen mode

Now you just need to use the helper that transify provides instead of vue-router.

<template>
  <!--This component replaces the <router-view> in your app  -->
  <PageTransitionHelper mode="out-in" :duration="1000" />
</template>
<script setup>
//You need to import the animation you want to use in the app
import { PageTransitionHelper } from "vue-transify";
</script>
Enter fullscreen mode Exit fullscreen mode

Now that we have our library completely setup we can tell the app what transitions to use in router index.js.

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import AboutView from '@/views/AboutView.vue'

const routes = [
  {
    path: '/',
    component: HomeView,
    meta: { transition: 'fade' }
  },
  {
    path: '/about',
    component: AboutView,
    meta: { transition: 'slideInUp' }
  }
]

export default createRouter({
  history: createWebHistory(),
  routes
})

Enter fullscreen mode Exit fullscreen mode

That's it . Vue-Transify will automatically read the meta add the transition to your pages.

If you want to know more about the library feel free to read the docs in github.
You can also check out the demo website to see the transitions in action

Top comments (0)