Vue listens for routes using route hook interceptors beforeEach and afterEach

  • 2021-09-20 19:21:33
  • OfStack

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

Definition: Routing hook is a function defined for users to do some special treatment when routing changes.

Generally speaking, vue provides three kinds of hooks, two functions 1, global hooks 2, hooks of a certain route 3, and hooks within components

Two functions:

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

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

Global hook function

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


// router.jsconst 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
    },
  }
 ]
})

router.beforeEach((to,from,next)=>{
 // console.log("to:",to);   // router Incoming routing object 
 // console.log("from:",from); //  The current navigation is about to leave the route 
 // console.log("next:",next); // Function, In the pipeline 1 If the execution is finished, the navigation state is  confirmed  (Confirmed); Otherwise; Otherwise false , terminate navigation. 
 if(to.name=='notSend'){
  next({
   name:'sort'
  })
  return
 }
 next()
})

export default router

Hook function of a route

As the name implies, it is a function written in a route, which is essentially the same as a function in a component.


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

Hook of routing component

You can define the following routing navigation hooks directly within the routing component


// *.vuebeforeRouteEnter
beforeRouteUpdate (2.2  Add )
beforeRouteLeave

Here is a simple hook function: It is and data, methods level.


beforeRouteLeave(to, from, next) {
  next()
},
beforeRouteEnter(to, from, next) {
  next()
},
beforeRouteUpdate(to, from, next) { //  Parameter updates for the same routing component 
  next()
},
data:{},
method: {}

Related articles: