2

I am looking for a solution to add and remove classes on components/elements outside of the <nuxt/> element in layouts/default.vue during page transitions in a Nuxt project.

As an example, I would like to animate a div in and then out before every page transition. Pseudo code below:

<!-- layouts/default.vue -->

<template>
  <site-curtain :class="{ 'is-active': isTransitioning == true }" /> // I would to apply this class during a page transition
  <nuxt />
</template>

Is there an obvious way in Nuxt to listen to the page transitions that I am missing? I have looked at vue-router's beforeRouteUpdate navigation guard but not sure if it's suitable?

Any help will be greatly appreciated!

kissu
  • 40,416
  • 14
  • 65
  • 133
strnr
  • 63
  • 5

1 Answers1

0

try this (I used this approach in one of my projects and it works fine):

first I defined a mixin as follows:

mixin/transition.js:

export default {
  beforeEnter() {
    this.$emit('transition', true);
  },
  afterEnter() {
    this.$emit('transition', false);
  },
}

then imported it in every page that I wanted to use the effect:

pages/about-us.vue

import transition from '@/mixin/transition';

export default {
  mixins: [transition],
  ...
}

then in the layout page I could listen to the transition event emited before and after the transition is done and get the payload sent with the event:

<template>
  <site-curtaion :class="{ 'is-active': isTransition }" />
  <nuxt @transition="isTransition = $event" />
</template>

and this is the data object of the layout component:

data() {
  return {
    isTransition: false,
  };
}

here is the resources I used to put together this solution:

Nuxt transition properties

Vue's javascript transition hooks

tony19
  • 125,647
  • 18
  • 229
  • 307
hamid niakan
  • 2,668
  • 1
  • 12
  • 25
  • Thanks for the reply. I have just implemented as above but it seems the `@transition` never fires in Nuxt and class is never added? Do I need to register `@transition` as custom event? – strnr Jan 12 '22 at 20:27
  • @strnr I'm so sorry! totally forgot to post the full solution, (project was quite for a long time ago and didn't check it out completely before posting my answer), anyway I updated the answer with the full solution, I hope it helps – hamid niakan Jan 12 '22 at 23:32