vue 路由钩子

1,421 阅读2分钟

全局路由钩子

1、router.beforeEach :进入路由前

router.beforeEach((to, from, next) => { 
  next();
});

to: 即将要进入的目标路由对象

from: 当前导航正要离开的路由对象

next: 跳转新路由,当前的导航被中断,重新开始一个新的导航。

  • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)

  • 跳转方式:next('path地址') 或 next({path:''}) 或 next({name:''})

  • next(false): 中断当前的导航。

2、router.beforeResolve :全局解析守卫

beforeRouteEnter后 调用

router.beforeResolve((to, from,next) => { 
  next();
});

3、router.afterEach :进入路由后

router.afterEach((to, from) => { 
  
});

独享路由钩子

调用顺序在全局前置守卫 beforeEach后面

{
  path: '/home',
  beforeEnter: (to, from, next) => { 
    next();
  }
}

组件中的路由钩子

1、beforeRouteEnter :进入路由前

调用顺序在独享路由守卫 beforeEnter后面不!能!获取组件实例this,可以通过传一个回调给next来访问组件实例,执行时机在mounted后面

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

2、beforeRouteUpdate

在当前路由改变,但是该 组件被复用 时(路由复用同一个组件时)调用,而这个钩子就会在这个情况下被调用。可以访问组件实例 this

beforeRouteUpdate ((to, from, next) => { 
  next();
});

3、beforeRouteLeave :路由离开时

导航离开该组件的对应路由时调用,可以访问组件实例this

beforeRouteLeave((to, from, next) => { 
  next();
});

路由导航解析流程

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