全局路由守卫

  1. const router = createRouter();
  2. // 前置
  3. router.beforeEach((to, from, next) => {})
  4. // 解析
  5. router.beforeResolve()
  6. // 后置
  7. router.afterEach()

路由守卫

  1. const router = new VueRouter({
  2. routes: [
  3. {
  4. path: '/index',
  5. compontent: index,
  6. beforeEnter: (to, from, next) => {}
  7. }
  8. ]
  9. })

组件守卫

  1. // 前置
  2. beforeRoute(to, from, next) {
  3. // 1. 不能用this
  4. // 2. 可以这样 next(vm => 访问实例)
  5. }
  6. // 更新
  7. beforeRouteUpdate(to, from, next) {
  8. }
  9. // 后置
  10. beforeRouterLeave(to, from, next) {
  11. }

顺序

  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 的回调函数,创建好的组件实例会作为回调函数的参数传入。