Vue Router Navigation Guards Explained

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.

See the Pen Vue Router Navigation Guards by Patrick O’Dacre (@patrickodacre) on CodePen.

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 let me know.

Comments, questions and constructive feedback are always welcome.