SoFunction
Updated on 2025-04-03

A detailed explanation of navigation guards in vue-router

What is a navigation guard

According to the official documentation,vue-routerThe navigation guards provided are mainly used to guard navigation through jump or cancellation. There are many ways to implant routing navigation here: global, single route-only, or component-level.

existvue-routerIn the process of routing navigation, navigation guard is a very important function. It allows you to add logical verification and processing during routing navigation, such as determining whether the user is logged in, if you are not logged in, you will jump to the login page, and if you are already logged in, you will jump to the homepage.

Category of Navigation Guards

existVue RouterThere are three types of navigation guard methods that can be used:

  • Global Guard:beforeEachandafterEach

  • Exclusive route guard:beforeEnter

  • In-component routing guard:beforeRouteEnterbeforeRouteUpdateandbeforeRouteLeave

Global Guard

The global guard is to intercept all routes in the entire application when the route is redirected and then perform some operations.

The global guard is divided intoGlobal front guardandGlobal rear guard

Global front guardIt is to intercept before the route jumps.Global rear guardIt is to intercept after the route jumps.

The use of global front guards is as follows:

((to, from, next) => {
  // ...
})

The use of global rear guard is as follows:

((to, from) => {
  // ...
})

Route exclusive guard

The exclusive route guard is to intercept a specific route in the application when the route is redirected and then perform some operations.

The use of route exclusive guards is as follows:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})

Guardian inside components

The guard within the component is a special guard method defined inside the component, which is used to handle component-level routing navigation. Common components guards include:

  • beforeRouteEnter: Called before the route enters the component, the component instance can not be accessed, but the component instance can be obtained through the callback function.

  • beforeRouteUpdate: Called when the current route is multiplexed, for example when the same component switches under different parameters.

  • beforeRouteLeave: Called before leaving the current route, you can ask the user whether to save unsaved data or perform other cleaning operations.

const UserDetails = {
  template: `...`,
  beforeRouteEnter(to, from) {
    // Called before rendering the corresponding route of the component is verified    // Cannot get component instance `this`!    // Because when the guard executes, the component instance has not been created yet!  },
  beforeRouteUpdate(to, from) {
    // Called when the current route changes, but the component is reused    // For example, for a path with dynamic parameters `/users/:id`, when jumping between `/users/1` and `/users/2`,    // Since the same `UserDetails` component is rendered, component instances are reused.  And this hook will be called in this case.    // Because when this happens, the component has been mounted, the navigation guard can access the component instance `this`  },
  beforeRouteLeave(to, from) {
    // Called when navigation leaves rendering the corresponding route of the component    // Like `beforeRouteUpdate`, it can access component instances `this`  },
}

Parameters of navigation guards

The parameters of the navigation guard are as follows:

  • to: The target routing object that is about to enter contains information such as the path, parameters, query parameters, etc. of the target route, which can be used to determine which route to navigate to.

  • from: The route that the current navigation is about to leave contains the path, parameters, query parameters and other information of the current route, which can be used to determine the status of the current route.

  • nextMethod: Used to control navigation behavior. It has the following usages:

    • next(): Allow navigation and continue to the next navigation operation.
    • next(false): Cancel navigation and terminate the current navigation operation.
    • next('/')ornext({ path: '/' }): Redirect to the specified path.
    • next(error): An error occurred in navigation, you can pass an error object to the next method.

The execution order of navigation guards

The execution order of navigation guards is as follows:

Global Front Guard -> Route Exclusive Guard -> Component Guard -> Global Back Guard

Use scenarios of navigation guards

Global front guard

  • Determine whether the user is logged in. If he is not logged in, he will jump to the login page. If he is already logged in, he will jump to the homepage.
((to, from, next) => {
  if ( === '/login') {
    next()
  } else {
    const token = ('token')
    if (!token) {
      next('/login')
    } else {
      next()
    }
  }
})

Global rear guard

  • Records the pages visited by the user.
((to, from) => {
  ('path', )
})

Route exclusive guard

  • Determine whether the user has permission to access a certain page, and if there is no permission, it will jump to the home page.
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        const token = ('token')
        if (!token) {
          next('/')
        } else {
          const role = ('role')
          if ( && (role) === -1) {
            next('/')
          } else {
            next()
          }
        }
      }
    }
  ]
})

Guardian inside components

  • Data preloading: Before entering the component, some data needs to be loaded first. Can be usedbeforeRouteEnterThe guards in the component call the interface to obtain data, and then enter the component after the data is loaded.
const Foo = {
  beforeRouteEnter(to, from, next) {
    fetchData().then(data => {
      next(vm => {
         = data; // Pass data to component instance      });
    });
  },
};
  • Routing parameter update: When the same component switches under different parameters, it may be necessary to update the component's data or status according to the new parameters. Can be usedbeforeRouteUpdateThe guards inside the component handle this situation.
const Baz = {
  beforeRouteUpdate(to, from, next) {
    if ( !== ) {
      // Request data again when the routing parameter id changes      ();
    }
    next();
  },
};
  • Data cleaning: Some cleaning operations need to be performed before leaving the current route, such as unsubscribe events, reset component status, etc. Can be usedbeforeRouteLeaveThe guards inside the component handle these operations.
const Bar = {
  beforeRouteLeave(to, from, next) {
    if (()) {
      if (confirm('Does the modified data be saved?  ')) {
        (); // Save modified data      }
    }
    next(); 
};
  • Page switching animation: Add transition animation effects when switching pages to improve user experience. Can be inbeforeRouteEnterandbeforeRouteLeaveThe logic for setting transition animations in the guards within the component.
const Qux = {
  beforeRouteEnter(to, from, next) {
    // Set the initial transition state before entering the component     = 'slide-in';
    next();
  },
  beforeRouteLeave(to, from, next) {
    // Set transition state before leaving the component     = 'slide-out';
    next();
  },
};

This is the article about this article about a detailed explanation of navigation guards in vue-router. For more related contents of vue-router navigation guards, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!