vue-router钩子执行顺序示例解析

 更新时间:2023年07月28日 08:53:15   作者:beckyyyy  
这篇文章主要为大家介绍了vue-router钩子执行顺序示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

Vue路由执行跳转

Vue的路由在执行跳转时,根据源码可知,调用了router中定义的navigate函数

function push(to: RouteLocationRaw) {
   return pushWithRedirect(to)
}
function replace(to: RouteLocationRaw) {
   return push(assign(locationAsObject(to), { replace: true }))
}
function pushWithRedirect(
    to: RouteLocationRaw | RouteLocation,
    redirectedFrom?: RouteLocation
  ): Promise<NavigationFailure | void | undefined> {
    // ...
    return (failure ? Promise.resolve(failure) : navigate(toLocation, from))/*调用navigate*/
      .catch((error: NavigationFailure | NavigationRedirectError) =>
        isNavigationFailure(error)
          ? // navigation redirects still mark the router as ready
            isNavigationFailure(error, ErrorTypes.NAVIGATION_GUARD_REDIRECT)
            ? error
            : markAsReady(error) // also returns the error
          : // reject any unknown error
            triggerError(error, toLocation, from)
      )
      .then((failure: NavigationFailure | NavigationRedirectError | void) => {
        if (failure) {
          // ...
        } else {
          // 执行finalizeNavigation完成导航
          // if we fail we don't finalize the navigation
          failure = finalizeNavigation(
            toLocation as RouteLocationNormalizedLoaded,
            from,
            true,
            replace,
            data
          )
        }
        // 触发`afterEach`
        triggerAfterEach(
          toLocation as RouteLocationNormalizedLoaded,
          from,
          failure
        )
        return failure
      })
}
function navigate(
    to: RouteLocationNormalized,
    from: RouteLocationNormalizedLoaded
  ): Promise<any> {
    let guards: Lazy<any>[]
    // ...
    // run the queue of per route beforeRouteLeave guards
    return (
      // 1.调用离开组件的`beforeRouteLeave`钩子
      runGuardQueue(guards)
        .then(() => {
          // 获取全局的的`beforeEach`钩子
          // check global guards beforeEach
          guards = []
          for (const guard of beforeGuards.list()) {
            guards.push(guardToPromiseFn(guard, to, from))
          }
          guards.push(canceledNavigationCheck)
          // 2.调用全局的`beforeEach`钩子
          return runGuardQueue(guards)
        })
        .then(() => {
          // 获取更新的路由其对应组件的`beforeRouteUpdate`钩子
          // check in components beforeRouteUpdate
          guards = extractComponentsGuards(
            updatingRecords,
            'beforeRouteUpdate',
            to,
            from
          )
          for (const record of updatingRecords) {
            record.updateGuards.forEach(guard => {
              guards.push(guardToPromiseFn(guard, to, from))
            })
          }
          guards.push(canceledNavigationCheck)
          // 3.调用复用组件的`beforeRouteUpdate`钩子
          // run the queue of per route beforeEnter guards
          return runGuardQueue(guards)
        })
        .then(() => {
          // 获取进入的路由自身的`beforeEnter`钩子
          // check the route beforeEnter
          guards = []
          for (const record of enteringRecords) {
            // do not trigger beforeEnter on reused views
            if (record.beforeEnter) {
              if (isArray(record.beforeEnter)) {
                for (const beforeEnter of record.beforeEnter)
                  guards.push(guardToPromiseFn(beforeEnter, to, from))
              } else {
                guards.push(guardToPromiseFn(record.beforeEnter, to, from))
              }
            }
          }
          guards.push(canceledNavigationCheck)
          // 4.调用新匹配路由的`beforeEnter`钩子
          // run the queue of per route beforeEnter guards
          return runGuardQueue(guards)
        })
        .then(() => {
          // NOTE: at this point to.matched is normalized and does not contain any () => Promise<Component>
          // clear existing enterCallbacks, these are added by extractComponentsGuards
          to.matched.forEach(record => (record.enterCallbacks = {}))
          // 获取进入的路由其对应组件的`beforeRouteEnter`钩子
          // check in-component beforeRouteEnter
          guards = extractComponentsGuards(
            enteringRecords,
            'beforeRouteEnter',
            to,
            from
          )
          guards.push(canceledNavigationCheck)
          // 5.调用新组件的`beforeRouteEnter`钩子
          // run the queue of per route beforeEnter guards
          return runGuardQueue(guards)
        })
        .then(() => {
          // 获取全局的的`beforeResolve`钩子
          // check global guards beforeResolve
          guards = []
          for (const guard of beforeResolveGuards.list()) {
            guards.push(guardToPromiseFn(guard, to, from))
          }
          guards.push(canceledNavigationCheck)
          // 6.调用全局的`beforeResolve`守卫
          return runGuardQueue(guards)
        })
        // catch any navigation canceled
        .catch(err =>
          isNavigationFailure(err, ErrorTypes.NAVIGATION_CANCELLED)
            ? err
            : Promise.reject(err)
        )
    )
  }
  // 触发`afterEach`
  function triggerAfterEach(
    to: RouteLocationNormalizedLoaded,
    from: RouteLocationNormalizedLoaded,
    failure?: NavigationFailure | void
  ): void {
    // navigation is confirmed, call afterGuards
    // TODO: wrap with error handlers
    afterGuards
      .list()
      .forEach(guard => runWithContext(() => guard(to, from, failure)))
  }

顺序执行

由上述源码中可以看出,由Promise then的链式调用保证了路由守卫按照以下顺序执行:

  • 旧的路由组件beforeRouteLeave
  • 全局配置的beforeEach
  • 复用的路由组件beforeRouteUpdate
  • 新路由的beforeEnter
  • 新路由组件的beforeRouteEnter
  • 全局配置的beforeResolve
  • navigate执行完毕后,会调用triggerAfterEach函数,触发afterEach

和官网文档上所写的是一样的。The Full Navigation Resolution Flow

以上就是vue-router钩子执行顺序的详细内容,更多关于vue-router钩子执行顺序的资料请关注脚本之家其它相关文章!

相关文章

  • element多选表格中使用Switch开关的实现

    element多选表格中使用Switch开关的实现

    当在做后台管理系统的时候,会用到用户的状态管理这个功能,本文主要介绍了element多选表格中使用Switch开关的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • vue菜单栏联动内容页面tab的实现示例

    vue菜单栏联动内容页面tab的实现示例

    本文主要介绍了vue菜单栏联动内容页面tab的实现示例,左侧菜单栏与右侧内容部分联动,当点击左侧的菜单,右侧会展示对应的tab,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • Vue使用pinia管理数据pinia持久化存储问题

    Vue使用pinia管理数据pinia持久化存储问题

    这篇文章主要介绍了Vue使用pinia管理数据pinia持久化存储问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Vue中父组件向子组件通信的方法

    Vue中父组件向子组件通信的方法

    可以使用props将父组件的数据传给子组件。子组件在接受数据时要显示声明props。下面通过一个例子给大家介绍Vue中父组件向子组件通信的方法,需要的朋友参考下吧
    2017-07-07
  • Vue2.0父组件与子组件之间的事件发射与接收实例代码

    Vue2.0父组件与子组件之间的事件发射与接收实例代码

    这篇文章主要介绍了Vue2.0父组件与子组件之间的事件发射与接收实例代码,需要的朋友可以参考下
    2017-09-09
  • Vue Class Component类组件用法

    Vue Class Component类组件用法

    这篇文章主要介绍了Vue Class Component类组件用法,组件 (Component) 是 Vue.js 最强大的功能之一,它是html、css、js等的一个聚合体,封装性和隔离性非常强
    2022-12-12
  • Vue el-table表头上引入组件不能实时传参解决方法分析

    Vue el-table表头上引入组件不能实时传参解决方法分析

    这篇文章主要介绍了Vue el-table表头上引入组件不能实时传参解决方法,总的来说这并不是一道难题,那为什么要拿出这道题介绍?拿出这道题真正想要传达的是解题的思路,以及不断优化探寻最优解的过程。希望通过这道题能给你带来一种解题优化的思路
    2022-11-11
  • 解决Vue使用百度地图BMapGL内存泄漏问题 Out of Memory

    解决Vue使用百度地图BMapGL内存泄漏问题 Out of Memory

    这篇文章主要介绍了解决Vue使用百度地图BMapGL内存泄漏问题 Out of Memory,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • vue实现页面上传文件夹压缩后传给服务器的操作

    vue实现页面上传文件夹压缩后传给服务器的操作

    这篇文章主要介绍了vue实现页面上传文件夹压缩后传给服务器的操作,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-09-09
  • Vue中实现父子组件双向数据流的三种方案分享

    Vue中实现父子组件双向数据流的三种方案分享

    通常情况下,父子组件的通信都是单向的,或父组件使用props向子组件传递数据,或子组件使用emit函数向父组件传递数据,本文将尝试讲解Vue中常用的几种双向数据流的使用,需要的朋友可以参考下
    2023-08-08

最新评论