SoFunction
Updated on 2025-04-04

Example analysis of the usage of hook function of vue-router

This article describes the usage of the hook function of vue-router. Share it for your reference, as follows:

Vue routing hooks can be roughly divided into three categories:

1. Global hook

Mainly include beforeEach and aftrEach,

The beforeEach function has three parameters:

  • to:router route object to enter
  • from: The route that the current navigation is about to leave
  • next:Function, perform a hook in the pipeline. If the execution is completed, the navigation status is confirmed; otherwise it is false, and the navigation is terminated.

AfterEach function does not need to pass next() function

This type of hook is mainly used to determine permissions and operations that need to be performed when the page is lost, such as:

//Use the hook function to transfer permissions to the route((to, from, next) => {
  const role = ('ms_username');
  if(!role &&  !== '/login'){
    next('/login');
  }else if(){
    // If it is administrator permission, you can enter. This is just a simple simulation of administrator permissions.    role === 'admin' ? next() : next('/403');
  }else{
    // Simple judgment: IE10 and below do not enter rich text editors, and this component is incompatible    if(('MSIE') > -1 &&  === '/editor'){
      .$alert('vue-quill-editor component is not compatible with IE10 and below browsers, please use a higher version of the browser
       Viewer view', 'Browser Incompatible Notification', {
        confirmButtonText: 'Sure'
      });
    }else{
      next();
    }
  }
})

2. Hooks in a single route

Mainly used to write the logic that needs to be executed when a specified route jumps

        {
          path: '/dashboard',
          component: resolve => require(['../components/page/'], resolve),
          meta: { title: 'System Home Page' },
          beforeEnter: (to, from, next) => {
           },
          beforeLeave: (to, from, next) => {
          }
        },

3. Component routing

It mainly includes beforeRouteEnter and beforeRouteUpdate , beforeRouteLeave . These hooks are written in the component and can also pass three parameters (to, from, next), and their functions are similar to the previous one.

 beforeRouteEnter(to, from, next) {
  next(vm => {
   if (
    vm.$('auth_key') &&
    vm.$.auth_key != ''
   ) {
    if (!(vm.$.auth_key)) {
     vm.$('/admin/noPermission')
    }
   }
  })
 },

I hope this article will be helpful to everyone's programming.