Mokkapps Logo

Vue Tip: Animate Child Component Before Route Leave

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
March 25, 2022
1 Minuten Lesezeit
|
- Ansichten

Vue Router provides a way to use transitions on your route components and animate navigations.

But sometimes, you might want to animate a specific (sub-)component before a route is left.

Therefore, you can use the onBeforeRouteLeave navigation guard combined with a ref to toggle the visibility of the component:

The v-if is necessary to trigger the animation. More at the official docs.

<template>
  <section class="body">
    <Transition name="image">
      <img v-if="showUI" src="../assets/image.svg" alt="Image" />
    </Transition>
  </section>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onBeforeRouteLeave } from 'vue-router';

const showUI = ref(true);

onBeforeRouteLeave((to, from, next) => {
  if (to.name === 'Home') {
    showUI.value = false;
    setTimeout(() => {
      next();
    }, 1000);
  } else {
    next();
  }
});
</script>

<style lang="scss">
.image-leave-active {
  transition: transform 1s ease;
}

.image-leave-to {
  transform: translateY(30vw) translateX(40vw) rotate(30deg);
}
</style>

Let’s take a closer look at the code inside onBeforeRouteLeave:

onBeforeRouteLeave((to, from, next) => {
  if (to.name === 'Home') {
    showUI.value = false;
    setTimeout(() => {
      next();
    }, 1000);
  } else {
    next();
  }
});

If the following route is anything other than Home, we allow the navigation and call next.

If the following route is Home, we toggle the component’s visibility by setting showUI to false. Next, we call setTimeout with 1 second to wait until the animation is done and then proceed with the route change by calling next.

The animation time is defined in our <style> block:

<style lang="scss">
.image-leave-active {
  transition: transform 1s ease;}

.image-leave-to {
  transform: translateY(30vw) translateX(40vw) rotate(30deg);
}
</style>


If you liked this tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github