Vue Tip: Animate Child Component Before Route Leave
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:
Info
The v-if
is necessary to trigger the animation. More at the official docs.
Let's take a closer look at the code inside onBeforeRouteLeave
:
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:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Use v-bind to Pass Multiple Props to Components
Instead of passing each property individually to a component, you can bind an object to it.
Vue Tip: Measure Performance
Learn some tools to measure the performance of your Vue application.