Official documentation: Navigation Guard

What are the route guards

Global routing hook:

  • beforeEach (to, from, next)
  • beforeResolve(to, from, next)
  • AfterEach (to, from) does not accept next and does not change the navigation itself

Route exclusive guard:

  • BeforeEnter (to, From, Next) is written in the configuration file
const routes = [
    {
        path: "/".name: "layout".beforeEnter(to, from, next) {
                // ...}}]Copy the code

Component route guard:

  • The beforeRouteEnter(to, from, next) cannot be obtainedthis, you can pass a callback using next(VM => {})
  • beforeRouteUpdate(to, from, next)
  • beforeRouteLeave(to, from, next)

BeforeRouteUpdate and beforeRouteEnter

If the matched rules are the same, beforeRouteUpdate is triggered. If the matched rules are different, beforeRouteEnter is triggered

For example:

  • /user= >/aboutThe triggerAboutThe component’sbeforeRouteEnter
  • /user/1= >/user/2The triggeruserThe component’sbeforeRouteUpdate

Here’s another puzzle: What if the routing rule was written like this:

const routes = [
    {
        path: "/user/:id".name: "user".component: User,
        props: true
    },
    {
        path: "/user".name: "user".component: User
    }
]
Copy the code

/user => /user/1 Since this route redirect matches two different rules, beforeRouteEnter is triggered

Route navigation trigger sequence

When routing navigation is triggered, two component routing hooks and the global hook function are called. The two components are deactivated and activated respectively, in the following order:

  • Navigation is triggered
  • Deactivate component: beforeRouteLeave
  • Global: beforeEach
  • Activate component: beforeEnter in route configuration
  • Parsing asynchronous components
  • Activate component: beforeRouteEnter
  • Global: beforeResolve
  • Navigation confirmed
  • Global: afterEach
  • Triggering DOM updates
  • Activate the component: Next in the beforeRouteEnter is called and the current component instantiation object is passed as a parameter to the callback function

When dynamic routing is configured, when /comp-a/1 and /comp-a/2 switch each other, the components are reused, so the navguards of the components are not triggered. In this case, the navguards are triggered in the following sequence:

  • Navigation is triggered
  • Global: beforeEach
  • Components: beforeRouteUpdate
  • Global: beforeResolve
  • Navigation confirmed
  • Global: afterEach
  • Triggering DOM updates
const routes = [
  {
    path: "/comp-a/:id".name: "comp-a".props: true.component: compA,
    // Routing guard in configuration
    beforeEnter: (to, from, next) = > {
      console.log(to.name, ": beforeEnter"); next(); }}]Copy the code

Test source code path: github.com/mkolp115977…