Home > Web Front-end > Vue.js > An in-depth analysis of navigation hooks in Vue-Router

An in-depth analysis of navigation hooks in Vue-Router

青灯夜游
Release: 2021-11-08 18:55:39
forward
2203 people have browsed it

This article will take you through something that must be asked in the interview---the navigation hook in Vue-Router. I hope it will be helpful to you!

An in-depth analysis of navigation hooks in Vue-Router

Navigation Guard

"Navigation" indicates that the route is changing.

vue-router The navigation guards provided are 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. [Related recommendations: "vue.js Tutorial"]

1. Global front guard----router.beforeEach

router.beforeEach Register a global front guard:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  //  to:要去哪个页面
  //  from:从哪里来
  //  next:它是一个函数。
  //     如果直接放行 next()
  //     如果要跳到其它页 next(其它页)
})
Copy after login

Sample code:

router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  const token = store.state.user.token
  const userId = store.state.user.userInfo.userId
  console.log(token, to.path, from.path)
  if (token) {
    if (to.path === '/login') { // 有 token还要去login
      next('/')
      NProgress.done() // 关闭进度条
    } else { // 有 token,去其他页面,放行
      if (!userId) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    if (to.path === '/login') { // 没有token,去login,放行
      next()
    } else {
      next('/login') // 没有token,去其他页面
      NProgress.done()
    }
  }
})
Copy after login

Summary

  • router.beforeEach (callback (three parameters))
  • In the navigation guard function, be sure to call next()
  • to.path: to is a routing object, path represents the path and is one of its attributes

2. Global post hook----router.afterEach

router.afterEach Register a global post-hook:

You can also register a global post-hook, but unlike guards, these hooks will not accept next The function will not change the navigation itself:

router.afterEach((to, from) => {
  // ...
})
Copy after login

3. Global resolution guard----router.beforeResolve

In 2.5.0 you can Use router.beforeResolve to register a global guard. This is similar to router.beforeEach, the difference is that before the navigation is confirmed, the guard is in all components at the same time and after the asynchronous routing component is parsed , the parsing guard is called.

4. Route-exclusive guards

You can define it directly in the routing configuration beforeEnter Guard:

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

5. Guards within the 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`
      }
    }
    Copy after login

    Complete navigation parsing process

    • Navigation is triggered.

    • Call the

      beforeRouteLeave guard in the deactivated component.

    • Call the global

      beforeEach guard.

    • Call

      beforeRouteUpdate guards (2.2) in reused components.

    • Call

      beforeEnter in the 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.

    For more programming-related knowledge, please visit:

    Introduction to Programming! !

    The above is the detailed content of An in-depth analysis of navigation hooks in Vue-Router. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template