Learn Vue Router Navigation Guards Quickly
Navigation Guards are a very useful tool, and will allow you to pull off some really complicated UI work.
Guards & Hooks
Looking at the documentation here, you see that Vue Router offers a series of guards and a single hook.
Each guard and hook allow you to interject some work at specific points as you go from route to route.
To really get to know which to use in a given situation, it helps to understand the order of events when navigating to a given route:
The Full Navigation Resolution Flow
- Navigation triggered
- Call leave guards in deactivated components
- Call global
beforeEach
guards - Call
beforeRouteUpdate
guards in reused components (2.2+) - Call
beforeEnter
in route configs - Resolve async route components
- Call
beforeRouteEnter
in activated components - Call global
beforeResolve
guards (2.5+) - Navigation confirmed.
- Call global
afterEach
hooks. - DOM updates triggered.
- Call callbacks passed to
next
inbeforeRouteEnter
guards with instantiated instances.
Types of Guards
Global Guards
- beforeEach()
- afterEach()
- beforeResolve()
Found on the ‘router’ object.
Per-Route Guard
- beforeEnter()
Found on each individual route definition object.
In-Component Guards
- beforeRouteEnter()
- beforeRouteUpdate()
- beforeRouteLeave()
Placed on the individual component’s option object.
Examples
Take a look at the pen below and pay close attention to the comments I’ve added to help you.
Good To Know
- each Guard has access to a
next()
function that must be called before the navigation will continue. - a callback passed into the
next()
function will receivethis
as an argument, giving you access to the instance of the component to which you are navigating.
// access someFunction() on the resolved route's component.
next(vm => {
vm.someFunction()
})
- beforeRouteUpdate() is a fantastic hook when reusing a component, as would be the case when going from
user/1
touser/2
route.
Found this helpful?
If this short post has helped you in any way, please remember to give this a recommendation below and post a brief comment to support me.
Comments, questions and constructive feedback are always welcome.
My name is Patrick O’Dacre, and I’m chief builder at BuildtoLearn.io — a place where growing developers can get more comfortable with full stack development by helping aspiring entrepreneurs build application prototypes.
If you’re interested in full stack JavaScript development and getting more experience with taking a full application from Zero to Production, visit BuildtoLearn.io and sign up for updates.