Search code examples
vue.jsvue-routertransition

Vue transition animation with router-view only works for the first transition


I want to make transitions between my navbar elements, so i'm using router-links. The transition works fine for the /about section, but for the others it completely stops working. If i'm on /something and return to /about, the transitions also works, but for other routes it doesn't.

Any advice of what i can do?

App.vue

<template>
  <div>
    <Navbar/>
    <div>
      <router-link to="/about"/>
      <router-link to="/experience"/>
      <router-link to="/education"/>
      <router-link to="/contact"/>
    </div>
    <Transition name="slide-fade" mode="out-in">
      <router-view/> 
    </Transition>
  </div>
</template>

<style>
  .slide-fade-enter-active {
    transition: all 0.3s ease-out;
  }
  .slide-fade-enter-from,
  .slide-fade-leave-to {
    transform: translateX(2em);
    opacity: 0;
  }
</style>

router.js

const routes = [
    {
        path:'/about',
        name: 'About',
        component: About
    },
    {
        path:'/experience',
        name: 'Experience',
        component: Experience
    },
    {
        path:'/education',
        name: 'Education',
        component: Education
    },
    {
        path:'/contact',
        name: 'Contact',
        component: Contact
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

export default router

Solution

  • Solved it! Had to change my router-view tag for this:

    <router-view v-slot="{ Component, route }">
          <Transition name="fade" mode="out-in">
            <div :key="route.name">  
              <component :is="Component"></component>
            </div>
          </Transition>
        </router-view>
    

    Shoutout to the original solution https://stackoverflow.com/a/70042452/18184367