VueのNavigation Guards

2 minute read

Navigation guards are provided by vue-router. Three ways to hook:

  • globally
  • per-route
  • in-component

NOTE:

  1. Params or query changes won’t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard.
  2. Make sure to always call the next function, otherwise the hook will never be resolved.

Global

 1const router = new VueRouter({ ... })
 2
 3// Before Guards
 4router.beforeEach((to, from, next) => {
 5  // ...
 6})
 7
 8// Resolve Guards
 9// beforeResolve guards will be called right before the navigation is confirmed
10// after all in-component guards and async route components are resolved
11router.beforeResolve((to, from, next) => {
12  // ...
13})
14
15// After Hooks
16router.afterEach((to, from) => {
17  // ...
18})

Pre-reoute

 1const router = new VueRouter({
 2  routes: [
 3    {
 4      path: '/foo',
 5      component: Foo,
 6      beforeEnter: (to, from, next) => {
 7        // ...
 8      }
 9    }
10  ]
11})

In-component

 1const Foo = {
 2  template: `...`,
 3  beforeRouteEnter (to, from, next) {
 4    // called before the route that renders this component is confirmed.
 5    // does NOT have access to `this` component instance,
 6    // because it has not been created yet when this guard is called!
 7    // However, you can access the instance by passing a callback to next. 
 8    // The callback will be called when the navigation is confirmed
 9    // and the component instance will be passed to the callback as the argument
10    beforeRouteEnter (to, from, next) {
11      next(vm => {
12        // access to component instance via `vm`
13      })
14    }
15  },
16  beforeRouteUpdate (to, from, next) {
17    // called when the route that renders this component has changed,
18    // but this component is reused in the new route.
19    // For example, for a route with dynamic params `/foo/:id`, when we
20    // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
21    // will be reused, and this hook will be called when that happens.
22    // has access to `this` component instance.
23  },
24  beforeRouteLeave (to, from, next) {
25    // called when the route that renders this component is about to
26    // be navigated away from.
27    // has access to `this` component instance.
28  }
29}

Resolve flow

  • Navigation triggered.
  • Call leave guards in deactivated components.
  • Call global beforeEach guards.
  • Call beforeRouteUpdate guards in reused components.
  • Call beforeEnter in route configs.
  • Resolve async route components.
  • Call beforeRouteEnter in activated components.
  • Call global beforeResolve guards.
  • Navigation confirmed.
  • Call global afterEach hooks.
  • DOM updates triggered.
  • Call callbacks passed to next in beforeRouteEnter guards with instantiated instances.
comments powered by Disqus