- This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
Navigation guard
concept
Navigation: Indicates that the route is changing
Vue-router provides navigation guards that are used to guard navigation by jumping or canceling. There are several opportunities for embedding route navigation: global, single route proprietary, or component level.
Navigation guard: includes global navigation guard and local navigation guard
Global guard
Vue-router has three guards globally
- Router. beforeEach: Global front-guard, before entering a route
- Router. beforeResolve: Global resolution guard, called after beforeRouteEnter call (uncommon)
- Router. afterEach: A global afterhook after entering a route
Global front guard
You can register a global front-guard using router.beforeeach:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) = > {
// To and from are both routing instances
// to: indicates the route to be jumped
// from: current route to leave
// next: function
})
Copy the code
- Next: Function: Be sure to call this method to resolve the hook. The execution depends on the call parameters of the next method.
- Next () : Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.
- Next (false) : interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset to the address corresponding to the FROM route.
- Next (‘/’) or next({path: ‘/’}) : jumps to a different address. The current navigation is interrupted and a new navigation is performed. You can pass any location object to next, and you can set options like replace: True, name: ‘home’, and any options used in router-link’s to prop or router.push.
- Next (error) : (2.4.0+) If the argument passed to Next is an error instance, the navigation is terminated and the error is passed to the callback registered with router.onerror ().
Note: If next(‘/’) or next({path: ‘/’}) is a path to release, then it must be checked in the
When do you let him in, or he’ll keep cycling.
Global parsing guard
2.5.0 new
// Global parse guard
router.beforeResolve((to,from.next) = >{})Copy the code
In 2.5.0+ you can register a global guard with router.beforeResolve. This is similar to router.beforeeach, the area
The parse guard is called before the navigation is confirmed and after all the intra-component guards and asynchronous routing components have been parsed.
Global post-hook
You can also register global post-hooks, however unlike guards, these hooks do not accept the next function nor change the navigation itself:
// Global post-hook
router.afterEach((to,form) = >{})Copy the code
Because: afterEach is called after the route has already jumped, the next function is not needed
Route exclusive guard
If you do not want to configure routes globally, you can configure guards for some routes individually
For example, configure a guard for the mainPage page
{
path: '/mainpage'.name: 'About'.component: About, // Route exclusive guard
beforeEnter:(to,from,next) = > {
if(from.name === '/mainpage/about'){ alert("This is from About.")}else{
alert("It's not from about.")
}next(); // must be called to proceed to the next operation. Otherwise it won't jump}}},Copy the code
Guards within components
Finally, you can define the following route navigators directly within the routing component:
- BeforeRouteEnter () : indicates before entering the route
- BeforeRouteUpdate () : route multiplexing of the same component
- BeforeRouteLeave () : leaves the current route
Take an example in Product
// Global parse 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.")}else{
alert("It's not from about.")
}
next(); // must be called to proceed to the next operation. Otherwise it won't jump}}},export default {
// beforeRouteUpdate is triggered when the current route changes but the component is being reused.For example, if the product/ Orders route to product/ CART uses the product. vue component, the beforeRouteUpdate will be triggered. Access tothisInstance. A complete navigation parsing process// This is not available because the component instance has not yet been created when this hook is called
beforeRouteEnter (to, from, next) {
console.log(to.name);
// If you want to get an instance
// next(vm=>{
// // The VM here is an instance of the component (this)
// });
next();
},
beforeRouteUpdate(to,from,next){
console.log(to.name, from.name);
next();
},
// Call this method when the route is about to leave
// For example, if the user wants to leave the page after editing something but not saving it, he/she needs to be reminded that he/she has not saved it yetSave, 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 go away}},Copy the code
- BeforeRouteUpdate is triggered when the current route changes but the component is being reused.
- For example, the route from product/ Orders to product/ CART uses the product. vue component
- The beforeRouteUpdate will be triggered. You can get this instance.
A complete navigation parsing process
1. Navigation is triggered.
2. Call the leave guard in the deactivated component (the page component that is about to leave). beforeRouteLeave
Call the global beforeEach guard.
4. Call the beforeRouteUpdate guard (2.2+) in the reused component.
5. Call (exclusive guard of routes) beforeEnter in route configuration.
6. Parse asynchronous routing components
7. Call beforeRouteEnter in the active component (the page component to be entered).
8. Call the global beforeResolve guard (2.5+).
9. Navigation is confirmed.
Call the global afterEach hook. All the hooks are triggered.
Trigger DOM updates.
12. Call the callback passed to Next in the beforeRouteEnter guard with the created instance.
The last
If it is helpful to you, I hope I can give 👍 comment collection three even!
I am an honest front end, free to answer questions, welcome to join small circle of friends! ❤
- Welcome to discuss in the comments section, the excavation officials will draw 100 nuggets in the comments section after the end of the Excavation project activity, see the details of the lucky draw in the event article, friends to discuss!!