Routing guard

Router.vuejs.org/zh/guide/ad…

  • Global guard: router.beforeEach, router.afterEach, router.beforeResolve
  • Exclusive guard of routes: beforeEnter
  • Component internal guard: beforeRouteEnter, beforeRouteUpdate (added in 2.2), beforeRouteLeave

Global guard

1. Router. BeforeEach (Global front-guard)

  1. Three parameters
  • Path Params Query Hash fullPath matched Name Meta (in this example, it can be used in this example)

  • From: (Route Route object) The Route that the current navigation is leaving

  • Next: (Function Function) be sure to call this method to resolve the hook.

  1. next
  • Next (when no arguments): Go to the next hook in the pipe, and if you go to the last hook function, the navigation state is confirmed
  • Next (‘/’) or next({path: ‘/’}): jumps to a different address. The current navigation is interrupted and a new navigation is performed.
  1. Application Scenarios:

Permission verification, intercept before jump

router.beforeEach((to, from, next) = > {
    if (to.meta.requireAuth) {
        // Determine whether the route requires login permission
        if (cookies('token')) {
            // Read token through encapsulated cookies. If present, name goes to next step. If not, jump back to login page
            next()// Do not add "path:/" to next, it will fall into an endless loop
        }
        else {
            next({
                path: '/login'.query: {redirect: to.fullPath}// Use path as a parameter to switch to this route after successful login}}})else {
        next()
    }
})
Copy the code

Router. BeforeResolve

In 2.5.0+ 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.

3. Global post-hook router.aftereach

  1. Router. beforeEach is before the page loads, whereas router.afterEach is after the page loads
  2. You can also register global post-hooks, however unlike guards, these hooks do not accept the next function nor change the navigation itself:
router.afterEach((to, from) => {
  // ...
})
Copy the code

Router Exclusive guard (Router inner hook)

You can define ++beforeEnter++ guards directly on the route configuration: these guards have the same method parameters as global front-guards.

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

Guard inside a component (hook inside a component)

1. 3 hooks

  • beforeRouteEnter
  • BeforeRouteUpdate (2.2 New)
  • beforeRouteLeave
const Foo = {
  template: `... `,
  beforeRouteEnter (to, from, next) {
    // called before the corresponding route to render the component is confirmed
    / / no! Can!!!! Get component instance 'this'
    // Because the component instance has not been created before the guard executes
  },
  beforeRouteUpdate (to, from, next) {
    // Called when the current route changes but the component is being reused
    // For example, for a path /foo/:id with dynamic parameters, when jumping between /foo/1 and /foo/2,
    // Since the same Foo component will be rendered, the component instance will be reused. And the hook will be called in that case.
    // Access component instance 'this'
  },
  beforeRouteLeave (to, from, next) {
    // called when navigating away from the component's corresponding route
    // Access component instance 'this'}}Copy the code

Application 2.

  1. Clears timers in the current component
  • If a component has a timer, run the beforeRouteLeave command to clear the timer during route switchover to avoid occupying memory:
beforeRouteLeave (to, from, next) {
  window.clearInterval(this.timer) // Clear timer
  next()
}
Copy the code
  1. Prevents a page from jumping when there is an open window or content that has not been saved
  • If there is important information on the page that needs to be saved before the user can jump to the page, or there is a pop-up box. Users should be prevented from jumping, combined with vuex status management (dialogVisibility is saved)
beforeRouteLeave (to, from, next) {
 // Check whether the status of the dialog box is displayed and whether the information is saved
 if (this.dialogVisibility === true) {
    this.dialogVisibility = false // Close the pop-up box
    next(false) // Go back to the current page
  }else if(this.saveMessage === false) {
    alert('Please save the information and exit! ') // Pop-up warning
    next(false) // Go back to the current page
  }else {
    next() // Otherwise jump is allowed
  }
Copy the code
  1. Save related content to Vuex or Session
  • When the user needs to close the page, public information can be saved to session or Vuex
beforeRouteLeave (to, from, next) {
    localStorage.setItem(name, content); // Save to localStorage
    next()
}
Copy the code

Complete navigation parsing process

  1. Navigation is triggered.
  2. Call the beforeRouteLeave guard in the deactivated component.
  3. Call the global beforeEach guard.
  4. Call the beforeRouteUpdate guard (2.2+) in the reused component.
  5. Call beforeEnter in routing configuration.
  6. Parse the asynchronous routing component.
  7. Call beforeRouteEnter in the activated component.
  8. Call the global beforeResolve guard (2.5+).
  9. Navigation confirmed.
  10. Call the global afterEach hook.
  11. Trigger a DOM update.
  12. Call the callback passed to Next in the beforeRouteEnter guard, and the created component instance is passed in as an argument to the callback.