全局路由钩子
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();
});
路由导航解析流程
- 导航被触发。
- 在失活的组件里调用
beforeRouteLeave守卫。 - 调用全局的
beforeEach守卫。 - 在重用的组件里调用
beforeRouteUpdate守卫 (2.2+)。 - 在路由配置里调用
beforeEnter。 - 解析异步路由组件。
- 在被激活的组件里调用
beforeRouteEnter。 - 调用全局的
beforeResolve守卫 (2.5+)。 - 导航被确认。
- 调用全局的
afterEach钩子。 - 触发 DOM 更新(
mounted)。 - 调用
beforeRouteEnter守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。