Vue Router Patterns Chapter 20
beforeRouteEnter
We can also take advantage of beforeRouteEnter to perform actions prior to entering the
component route. Here's an example:
beforeRouteEnter(to, from, next) {
console.log(`I'm called before entering the route!`)
next();
}
We still have to call next to pass the stack down to the next route handler.
beforeRouteLeave
We can also hook into beforeRouteLeave to perform actions whenever we're navigating
away from a route. As we're already on this route within the context of this hook, we have
access to the component instance. Let's look at an example:
beforeRouteLeave(to, from, next) {
console.log(`I'm called before leaving the route!`)
console.log(`I have access to the component instance, here's proof!
Name: ${this.name}`);
next();
}
Once again, we have to call next in this instance.
Global router hooks
We've looked at component Navigation Guards and while these work on a component-by-
component basis, you may want to establish global hooks that listen to navigation events.
beforeEach
We can use router.beforeEach to listen for routing events globally across the
application. This is worth using if you have authentication checks or other pieces of
functionality that should be used in every route.