SoFunction
Updated on 2025-04-07

Vue uses routing hook interceptors beforeEach and afterEach to listen for routes

When routing jumps, we need some permission judgment or other operations. At this time, you need to use the routing hook function.

Definition: The routing hook is mainly a function defined by the user to perform some special processing when the route changes.

Generally speaking, vue provides three types of hooks, two functions: 1. Global hooks 2. Hooks for a certain route 3. Hooks within component

Two functions:

1. (function(to,form,next){}) /*Execute before jump*/

2. (function(to,form)}{}) /*Judge after jump*/

Global hook function

As the name suggests, it is a function that is globally valid

//  router = new Router({
 routes: [
  {
   path: '/',
   name: 'sideBar',
   component: sideBar,
   children:[
    {
     path:'/',
     name:'sort',
     component:sort
    },
    {
     path:'/addNewSort',
     name:'addNewSort',
     component:addNewSort
    },
    {
     path:'/notSend',
     name:'notSend',
     component:notSend
    },
    {
     path:'/sended',
     name:'sended',
     component:sended
    },
  }
 ]
})

((to,from,next)=>{
 // ("to:",to); // router is about to enter // ("from:",from); // The route that the current navigation is about to leave // ("next:",next); // Function, perform a hook in the pipeline. If the execution is completed, the navigation status is confirmed; otherwise it is false, terminate the navigation. if(=='notSend'){
  next({
   name:'sort'
  })
  return
 }
 next()
})

export default router

A hook function for a route

As the name suggests, it is a function written in a certain route, which is essentially no different from functions within components.

//  router = new VueRouter({
 routes: [
  {
   path: '/login',
   component: Login,
   beforeEnter: (to, from, next) => {
    // ...
   },
   beforeLeave: (to, from, next) => {
    // ...
   }
  }
 ]
})

Routing component hook

The following routing navigation hooks can be defined directly within the routing component

// *.vuebeforeRouteEnter
beforeRouteUpdate (2.2 New)
beforeRouteLeave

Here we briefly talk about the usage of hook function: it is on par with data and methods.

beforeRouteLeave(to, from, next) {
  next()
},
beforeRouteEnter(to, from, next) {
  next()
},
beforeRouteUpdate(to, from, next) { // Update parameters for the same routing components  next()
},
data:{},
method: {}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.