Learn Vue Router Navigation Guards Quickly

Patrick O'Dacre
Vue by Example
Published in
2 min readJun 14, 2017

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

  1. Navigation triggered
  2. Call leave guards in deactivated components
  3. Call global beforeEach guards
  4. Call beforeRouteUpdate guards in reused components (2.2+)
  5. Call beforeEnter in route configs
  6. Resolve async route components
  7. Call beforeRouteEnter in activated components
  8. Call global beforeResolve guards (2.5+)
  9. Navigation confirmed.
  10. Call global afterEach hooks.
  11. DOM updates triggered.
  12. Call callbacks passed to next in beforeRouteEnter 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 receive this 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 to user/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.

--

--

Patrick O'Dacre
Vue by Example

Coffee-fueled Programmer. I like making games and web things.