Home  >  Article  >  Web Front-end  >  What are the navigation guards of Vue?

What are the navigation guards of Vue?

青灯夜游
青灯夜游Original
2021-12-22 18:31:065642browse

Navigation guards include: 1. Global pre-guard "beforeEach"; 2. Global parsing guard "beforeResolve"; 3. Route-exclusive guard "beforeEnter"; 4. Guard within the component "beforeRouteEnter", "beforeRouteLeave".

What are the navigation guards of Vue?

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

The navigation guard provided by vue-router is mainly used to guard navigation by jumping or canceling. There are multiple opportunities to build into the route navigation process: globally, exclusive to a single route, or at the component level.

Remember that changes to parameters or queries will not trigger entry/leave navigation guards. You can respond to these changes by observing the $route object, or using the beforeRouteUpdate in-component guard.

Global front guard

You can use router.beforeEach to register a global front guard:

const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
  // ...
})

When a navigation is triggered, the global front guard Set guards are called in the order they are created. Guards are parsed and executed asynchronously. At this time, the navigation is waiting until all guards are resolved.

Each guard method receives three parameters:

  • to: Route: The target routing object to be entered

  • from: Route: The route that the current navigation is about to leave

  • next: Function: This method must be called to resolve this hook. The execution effect depends on the calling parameters of the next method.

    • next(): Proceed to the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed.

    • next(false): Interrupt current navigation. If the browser's URL changes (perhaps manually by the user or by the browser's back button), the URL address will be reset to the address corresponding to the from route.

    • next('/') or next({ path: '/' }): Jump to a different address. The current navigation is interrupted and a new navigation is started. You can pass an arbitrary location object to next, and options such as replace: true, name: 'home', and any options used in router-link's to prop or router.push are allowed to be set.

    • next(error): (2.4.0) If the parameter passed to next is an Error instance, the navigation will be terminated and the error will be passed to router.onError() Registered callback.

# Ensure that the next function is called exactly once in any given navigation guard. It can appear more than once, but only if all logical paths do not overlap, otherwise the hook will never be parsed or an error will be reported. Here's an example of redirecting to /login when the user fails to authenticate:

// BAD
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  // 如果用户未能验证身份,则 `next` 会被调用两次
  next()
})
// GOOD
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

Global Resolution Guard

New in 2.5.0

In 2.5.0 you can use router.beforeResolve to register a global guard. This is similar to router.beforeEach , except that the parsing guard is called before the navigation is confirmed, and after all in-component guards and async routing components have been parsed.

Routing-exclusive guards

You can directly define beforeEnter guards in the routing configuration:

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

The methods of these guards and global pre-guards The parameters are the same.

Guards within the component

Finally, you can define the following route navigation guards directly within the routing component:

  • beforeRouteEnter

  • beforeRouteUpdate (new in 2.2)

  • beforeRouteLeave

const Foo = {
  template: `...`,
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate(to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}

beforeRouteEnter The guard cannot access this, Because the guard is called before the navigation is confirmed, the new component that is about to appear has not yet been created.

However, you can access the component instance by passing a callback to next. Execute the callback when the navigation is confirmed, and pass the component instance as the parameter of the callback method.

beforeRouteEnter (to, from, next) {
  next(vm => {
    // 通过 `vm` 访问组件实例
  })
}

Note that beforeRouteEnter is the only guard that supports passing callbacks to next. For beforeRouteUpdate and beforeRouteLeave, this is already available, so passing callbacks is not supported because it is not necessary.

beforeRouteUpdate (to, from, next) {
  // just use `this`
  this.name = to.params.name
  next()
}

This leave guard is usually used to prevent users from leaving suddenly before saving changes. This navigation can be canceled with next(false).

beforeRouteLeave (to, from, next) {
  const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
  if (answer) {
    next()
  } else {
    next(false)
  }
}

Complete navigation parsing process

  • Navigation is triggered.

  • Call the beforeRouteLeave guard in the deactivated component.

  • Call the global beforeEach guard.

  • Call the beforeRouteUpdate guard (2.2) in the reused component.

  • Call beforeEnter in routing configuration.

  • Resolve asynchronous routing components.

  • Call beforeRouteEnter in the activated component.

  • Call the global beforeResolve guard (2.5).

  • Navigation confirmed.

  • Call the global afterEach hook.

  • Trigger DOM update.

  • Call the callback function passed to next in the beforeRouteEnter guard, and the created component instance will be passed in as a parameter of the callback function.

[Related recommendations: "vue.js tutorial"]

The above is the detailed content of What are the navigation guards of Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Is axios in vue?Next article:Is axios in vue?