流程
before...最后的参数是next(),必须调用
- 导航被触发。
- 在失活的组件里调用离开守卫。
- 调用全局的
beforeEach守卫。 - 在重用的组件里调用
beforeRouteUpdate守卫。 - 在路由配置里调用
beforeEnter。 - 解析异步路由组件。
- 在被激活的组件里调用
beforeRouteEnter。 - 调用全局的
beforeResolve守卫。 - 导航被确认。
- 调用全局的
afterEach钩子。 - 触发
DOM更新。 - 用创建好的实例调用
beforeRouteEnter守卫中传给next的回调函数
- matcher: 替换
- match: 匹配
- addRoutes: 添加
全局导航守卫
- 前:
router.beforeEach((to, from, next) => { }) - 后:
router.afterEach((to, from,) => { }) - 单个路由:
beforeEnter(to, from ,next) => { } - 组件内
beforeRouteEnter(to, from, next){ }不能获取组件实例 this
beforeRouteUpdate(to, from){ }beforeRouteLeave(to, from){ }
EG
const routes = [{
path: '/repository',
component: Repository,
meta: {
requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的
},
}]
router.beforeEach((to, from, next) => {
if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
if (store.state.token) { // 通过vuex state获取当前的token是否存在
next();
}
else {
next({
path: '/login',
query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
}
else {
next();
}
})

本文深入探讨Vue-Router的导航流程,包括全局导航守卫的使用,如beforeEach、afterEach等,并通过具体例子阐述如何在不同阶段拦截和控制路由跳转。同时,讲解了在组件内守卫的限制及其应用。
1098

被折叠的 条评论
为什么被折叠?



