There are three types of route guards. 1. Global guard. 2. Route exclusive guard. 3. Guards within components

1. The global guard (which is triggered every time a route jumps) has two hook functions beforeEach and afterEach.

  Now I’m going to print out the router so you can see it

This beforeEach and afterEach are both prototypes of the router. In fact, from the diagram we can see that they are a function, now we can see how it is probably used, passing in a function and letting vue encapsulate the code to call the function we passed in (if you are interested in the source code, the principle is similar to the source code of Promise).

1. Use router. BeforeEach ((to, from, next) => {}) Hook before entering a route. The function passed in takes three arguments to, form, and next. Where to is the target (page to enter) to be entered. Form Currently navigates the route that is leaving (the page that is currently leaving). Next is a function. Using next() confirms departure, next(false) interrupts current navigation, and next(‘/a’) allows it to route to A.

Router. AfterEach ((to, from) => {}) router. AfterEach ((to, from) => {}) router

2. Route exclusive guard, written in the right route inside

Such as:

His to form is the same as above

3. A guard within a component is used within a component as the name implies. Usage: Can be written directly to components

The official puzzle I think is that beforeRouteEnter has not entered the route yet. All beforeRouteEnter’s this is undefined. BeforeRouteEnter is executed before beforeCreate. To, form, next and beforeEach are the same.

BeforeRouteLeave it is triggered when it leaves the route. It can access this because it hasn’t actually left the component yet, so it can use this.