Personal Understanding:

  • In the process of route switching is navigation;
  • Set navigation, in the process of switching restrictions, restrictions implemented, is the guard succeeded;
The following combined with the summary of the various gods, wang Haihan.

I. Classification of navigation guards

1. There are 3 navigational guards

  • Global guard
  • A single route has an exclusive guard
  • Guards within components

2. Each takes 3 parameters except afterEach guard.

  • To: indicates the destination route to be entered
  • From: To leave the current route
  • Next: Control route execution (mandatory), be sure to call this method to resolve the hook

3. Next 4 behaviors:

next(); // The hook is ready for the next route; Navigation Guard status: Confirmed Next (false); // Interrupts the current route jump behavior next('/'); Next ({path: '/'}) // Enter the corresponding route according to the route jump condition, enter a new navigation next(new Error) // interrupt the route, the Error will be passed to the router.onerror () registered callbackCopy the code

Two, three kinds of navigation guard details

1. Global routing guard (3)

  • Mount to the Router instance
  • Used to control each hop of the route

1.1. BeforeEach: Global front-guard

const router = new VueRouter({ ... }) router.beforeEach((to, from, Next) => {// to => route A => route b => route B => route B A => b // next Redirects to a page next("/login")})Copy the code

Function: Used for login authentication

router.beforeEach((to, from, next) => { if (to.name ! == 'Login' && ! isAuthenticated) next({ name: 'Login' }) else next() })Copy the code

BeforeResolve: Global parsing guard

You can register a global guard with router.beforeResolve. This is similar to router.beforeeach, except that the parse guard is called before the navigation is confirmed and after all the intra-component guards and asynchronous routing components are parsed.

1.3 afterEach: Global post-hook guard

These hooks do not accept the next function nor change the navigation itself:

router.afterEach((to, from) => {
  // ...
})
Copy the code

2. Exclusive guard for a single route (1)

2.1、 beforeEnter

You can define the beforeEnter guard directly on the route configuration; A guard function that is executed only after entering the current page;

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
Copy the code

3. Guards inside the component (3)

3.1, beforeRouteEnter

  • Called before the corresponding route to render the component is confirmed.
  • Key points:Cannot get this instance. Because the component instance has not been created before the guard executes;
  • Order:BeforeEach and exclusive guard beforeEnter before global beforeResolve and afterEach are called;
const Foo = { template: `... `, beforeRouteEnter(to, from, next) { }, }Copy the code
  • Solution: beforeRouteEnterThe guardsCan’taccessthisBecause the guard is called before the navigation is confirmed, the upcoming new component has not yet been created. You can do this by passing a callback tonextTo access the component instance. The callback is executed when the navigation is validated, and the component instance is taken as an argument to the callback method.
BeforeRouteEnter (to, from, next) {next(vm => {// access component instance through 'VM'})}Copy the code

3.2, beforeRouteUpdate

  • Called when the current route changes but the component is being reused;
  • Since the same Foo component will be rendered, the component instance will be reused. And this hook will be called in that case;
  • Component instances can be accessedthis
const Foo = { template: `... ` beforeRouteUpdate(to, from, next) { }, }Copy the code

3.3, beforeRouteLeave

  • Called when navigating away from the component’s corresponding route
  • Component instances can be accessedthis
BeforeRouteLeave (to, from, next) {// Call when navigating away from the corresponding route of the component // Access component instance 'this'}Copy the code

BeforeRouteLeave Usage scenarios:

  1. If a timer exists in a component and needs to be cleared, route switchover prevents memory occupation.
  2. Save public information to session or VUEX;
  3. This navigation can be used when the page has an open window, or when there is no savenext(false)To unblock a page redirect as shown in the following example:
beforeRouteLeave (to, from, next) { const answer = window.confirm('Do you really want to leave? you have unsaved changes! ') if (answer) { next() } else { next(false) } }Copy the code

4. Complete navigation parsing

  1. Navigation is triggered.
  2. Called in a deactivated componentbeforeRouteLeaveThe guards.
  3. Call globalbeforeEachThe guards.
  4. Called in a reused componentbeforeRouteUpdateGuard (+ 2.2).
  5. Called in the routing configurationbeforeEnter.
  6. Parse the asynchronous routing component.
  7. Called in the active componentbeforeRouteEnter.
  8. Call globalbeforeResolveGuard (+ 2.5).
  9. Navigation confirmed.
  10. Call globalafterEachHook.
  11. Trigger a DOM update.
  12. callbeforeRouteEnterGuard passnextThe created component instance is passed in as an argument to the callback function.