current position:Home>Quickly understand Vue routing, navigation guard and in-depth analysis. [Award for comments]

Quickly understand Vue routing, navigation guard and in-depth analysis. [Award for comments]

2022-01-29 15:24:06 Front end honest man

Navigation guard

Concept

“ Navigation ” Indicates that the route is changing

vue-router The navigation guard provided is mainly used to guard the navigation by jumping or canceling . There are many opportunities to implant the routing navigation process in : Overall , Single route exclusive , Or component level .

Navigation guard : Include Global navigation guard and Local navigation guard

Global guard

vue-router There are three guards

  1. router.beforeEach : Front guard of the whole situation , Before entering the route
  2. router.beforeResolve : Global analysis guard , stay beforeRouteEnter Call after call ( Not commonly used )
  3. router.afterEach : Global post hook , After entering the route

Front guard of the whole situation

You can use router.beforeEach Register a global front guard :

const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// to and from All are routing instances 
// to: Route to jump to 
// from: Now the route to leave 
// next: function 
})
 Copy code 
  1. next: Function : Be sure to call this method resolve This hook . Execution depends on next Method call parameters .
  2. next() : Go to the next hook in the pipe . If all the hooks are finished , The state of navigation is confirmed ( Confirmed ).
  3. next(false) : Interrupt current navigation . If the browser's URL Changed the ( It may be the user's manual or browser Back button ), that URL Address will be reset to from The address corresponding to the route .
  4. next('/') perhaps next({ path: '/' }) : Jump to a different address . The current navigation is interrupted , Then take a new navigation . You can go to next Passing objects anywhere , And allow settings such as replace: true 、 name: 'home' Options like that, and anything that's used in router-link Of to prop or router.push Options in .
  5. next(error) : (2.4.0+) If you pass in next The parameter of is a Error example , The navigation will be terminated and the error will Be passed on to router.onError() Registered callbacks .

Be careful : If it is next('/') perhaps next({ path: '/' }), Just bring the path to release , Then there must be judgment , stay

When to release him , Or he'll keep cycling .

Global analysis guard

2.5.0 newly added

//  Global analysis guard  
router.beforeResolve((to,from.next) => { })
 Copy code 

stay 2.5.0+ You can use it. router.beforeResolve Sign up for a global guard . This sum router.beforeEach similar , District

Not before the navigation is confirmed , At the same time, after guard and asynchronous routing components in all components are resolved , Parse guard is called .

Global post hook

You can also register the global post hook , But unlike guards , These hooks won't accept next Functions do not change the navigation itself :

//  Global post hook 
 router.afterEach((to,form) => { })
 Copy code 

because :afterEach When called , Route jump completed , So no need next function

Route exclusive guard

If you don't want to configure routing globally , Some routes can be configured separately

such as : to mainpage The page is configured separately

{ 
path: '/mainpage', 
name: 'About', 
component: About, //  Route exclusive guard  
beforeEnter:(to,from,next) => {
 if(from.name === '/mainpage/about'){ alert(" This is from about To the ") 
   }else{
 alert(" This is not from about To the ") 
   }next(); //  Must be called for the next operation . Otherwise it won't jump  
 }
} 
},
 Copy code 

The guards in the component

Last , You can directly define the following route navigation guards in the route component :

  • beforeRouteEnter(): Before entering the route
  • beforeRouteUpdate(): When routes reuse the same component
  • beforeRouteLeave(): When leaving the current route

stay Product For example

//  Global analysis guard 
router.beforeResolve((to,from.next) => {
})
//  Global post hook 
router.afterEach((to,form) => {
})
{
path: '/mainpage',
name: 'About',
component: About,
//  Route exclusive guard 
beforeEnter:(to,from,next) => {
if(from.name === '/mainpage/about'){
alert(" This is from about To the ")
}else{
alert(" This is not from about To the ")
}
next(); //  Must be called for the next operation . Otherwise it won't jump 
}
}
},
export default {
//  Guard inside the assembly beforeRouteUpdate The trigger condition is : The current route changes , But when the component is reused .
 for instance :product/orders To product/cart This route , It's all reused  Product.vue  This component , This is the time 
beforeRouteUpdate Will be triggered . Can be obtained this example .
 A complete navigation analysis process 
//  Because when this hook is called , The component instance has not been created yet , So you can't get this
beforeRouteEnter (to, from, next) {
console.log(to.name);
//  If you want to get an instance 
// next(vm=>{
// //  there vm Is an instance of a component (this)
// });
next();
},
beforeRouteUpdate(to,from,next){
console.log(to.name, from.name);
next();
},
//  This method is called when the route is about to leave 
//  for instance , The user edited something , But it hasn't been saved yet , At this time, he will leave this page , Just remind him , Not yet 
 save , Whether to leave 
beforeRouteLeave (to, from, next) {
const leave = confirm(" Are you sure you want to leave ?");
if(leave) next() //  Leave 
else next(false) //  Don't leave 
},
}
 Copy code 
  • beforeRouteUpdate The trigger condition is : The current route changes , But when the component is reused .
  • for instance :product/orders To product/cart This route , It's all reused Product.vue This component , This is the time
  • beforeRouteUpdate Will be triggered . Can be obtained this example .

A complete navigation analysis process

1、 Navigation is triggered .

2、 In the inactivated components ( About to leave the page component ) Inside call leave guard . beforeRouteLeave

3、 Call global beforeEach The guards .

4、 Called in a reused component beforeRouteUpdate The guards (2.2+).

5、 Call... In routing configuration ( Route exclusive guard ) beforeEnter.

6、 Resolve asynchronous routing components

7、 In the activated component ( About to enter the page component ) Call inside beforeRouteEnter.

8、 Call global beforeResolve The guards (2.5+).

9、 Navigation confirmed .

10、 Call global afterEach hook . All the hooks are triggered .

11、 Trigger DOM to update .

12、 Call... With the created instance beforeRouteEnter Pass it to next Callback function for .

Last  

If it helps you , I hope I can give you a comment collection for three times !

I'm an honest man , Answer questions free of charge , Welcome to Xiaobian's circle of friends !

  • Welcome to discuss in the comment area , Nuggets officials will be in Digging force Star Program After the event , In the comment area Pumping 100 Physical objects around Nuggets , For details of the lucky draw, see the activity article , The little partner discussed it !!

copyright notice
author[Front end honest man],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/01/202201291524043545.html

Random recommended