流程
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();
}
})