DEV Community

Cover image for Learn Vue Router Navigation Guards [VueJS]
Patrick O'Dacre
Patrick O'Dacre

Posted on • Updated on

Learn Vue Router Navigation Guards [VueJS]

Subscribe to my YouTube channel for more tutorials on working with VueJS and AdonisJS -- an MVC framework for NodeJS!

Watch the Video + Fork the Pen

Check out the CodePen here:

Navigation Guards are a very useful tool; they can help you to pull off some really complicated UI work.

The Guards

Looking at the documentation here, you see that Vue Router offers a series 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.

Each guard allows 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 in beforeRouteEnter guards with instantiated instances.

Found this helpful?

Let me know if this has helped you! Post a comment below, and subscribe to my YouTube channel to make sure you don't miss my future tutorials on VueJS and NodeJS.

Top comments (0)