Thomas Miller
Thomas Miller

Reputation: 115

Nuxt.js page transitions, @leave never executing

I'm trying to have page transitions using with nuxt and Greensock (gsap), I can't seem to get it working. I don't want to animate page transitions using css only, because I want to easily chain animations on different elements.

Previously, with Vue I could simply use:

<transition @enter="enter" @leave="leave" appear mode="out-in">
  <router-view />
</transition>

export default {
  methods: {
    enter(el, done) {
      console.log('enter');
      // ... gsap animation code
    },
    leave(el, done) {
      console.log('leave');
      // ... gsap animation code
    }
  }
}

Now, with Nuxt, I can't seem to get it working. I use the exact same code in layouts/default.vue. Except I replace <router-view/> with <nuxt/>.

The "enter", "beforeEnter" methods works fine. It gets called on the initial page load, as well as anytime I change pages. However, the "leave" method never gets called.

What am I not understanding? I just need one place to manage all of my page transitions with javascript. I've been googling for a while now, looking through lots of examples, I can't seem to figure out what I'm doing wrong.

Upvotes: 1

Views: 3005

Answers (2)

Slava Nossar
Slava Nossar

Reputation: 171

Spent a while trying to solve the same problem, and as far as I can tell you can't use the <transition> component to specify JS hook callbacks around a <nuxt/> component, presumably due to Nuxt handling routing differently.

You need to define the transition property on each page, where enter() and leave() are specific to that particular page. For example, if you are on the Home page and navigate to the About page, Home's leave()and About's enter() will both trigger.

You can use a mixin to simplify adding different transitions to different pages:

~/mixins/transitions.js

export const typeA = {
  transition: {
    ...
  }
}

export const typeB = {
  transition: {
    ...
  }
}

Component

import { typeA } from '~/mixins/transitions'

export default {
  mixins: [
    typeA
  ]
}

You can also define a default transition in nuxt.config.js, but you will only have access to the page element, which might not be suitable for more complex transitions.

Upvotes: 2

Leo Seyers
Leo Seyers

Reputation: 340

I had the same issue, I followed @mstslv and used transition property on page components, it's the best solution so far to get proper results. You can programmatically do transitions by checking this.$route.path for instance.

If you want to avoid redundancy, you can use the following code

import transition from "~/plugins/transitions"

export default {
..
transition,
..
}

Upvotes: 0

Related Questions