Skip to content

Vue-router路由模式、守卫、解析流程

2024-08-19

vue-router-xmind

一、路由模式:

  • 1.Hash

    • 浏览器刷新与页面跳转

      1. hash是页面中快速定位的对应Id锚点的方式;
      2. location.hash可获取hash值;
      3. location.assignlocation.replace可以修改hash值;
    • 监听路由变化

      1. 浏览器提供了一个hashchange事件
      2. 使用onhashchange的全局函数
      3. 使用addEventListen('hashchange', fn)
  • 2. History(HTML5)

    • 浏览器刷新与页面跳转

      • html5对history进行了拓展,提供了两个新的API,来修改URL时不会刷新浏览器页面
        1. history.pushState:对应上面的location.assign
        2. history.replaceState:对应上面的location.replace
    • 监听路由变化

      1. 使用popstate事件来监听
      2. onPopState事件,同上
  • 3.Memory

    • 不会自动触发初始路由
    • 适合SSR,不会有历史记录

二、路由守卫

1.全局

  • 全局前置守卫:router.beforeEach
  • 全局解析守卫:router.beforeResolve
  • 全局后置守卫:router.afterEach

2.独享守卫

js
const routes = [
  {
    path: '/users/:id',
    component: UserDetails,
    beforeEnter: [removeQueryParams, removeHash],
  },
  {
    path: '/about',
    component: UserDetails,
    beforeEnter: [removeQueryParams],
  },
]

3.组件内守卫

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

resolve process

三、完整的导航解析流程

详见官方文档

  1. 导航被触发。
  2. 在失活的组件里调用 beforeRouteLeave 守卫。
  3. 调用全局的 beforeEach 守卫。
  4. 在重用的组件里调用 beforeRouteUpdate 守卫(2.2+)。
  5. 在路由配置里调用 beforeEnter
  6. 解析异步路由组件。
  7. 在被激活的组件里调用 beforeRouteEnter
  8. 调用全局的 beforeResolve 守卫(2.5+)。
  9. 导航被确认。
  10. 调用全局的 afterEach 钩子。
  11. 触发 DOM 更新。
  12. 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。

参考

github参考地址:https://github.com/vuejs/vue-router/blob/dev/src/index.js

Vue-router3.x官方文档:https://v3.router.vuejs.org/zh/

花海相伴