目录
beforeEach
全局前置路由守卫,基础用法如下:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
next方法解析
在路由守卫中,只有next()
是放行,其他的诸如:next('/logon') 、 next(to) 或者 next({ ...to, replace: true })
都不是放行,而是:中断当前导航,执行新的导航。
vue-router 动态加载路由
在addRoutes()
之后第一次访问被添加的路由会白屏,这是因为刚刚addRoutes()
就立刻访问被添加的路由,然而此时addRoutes()
没有执行结束,因而找不到刚刚被添加的路由导致白屏。因此需要从新访问一次路由才行。
此时就要使用next({ ...to, replace: true })
来确保addRoutes()
时动态添加的路由已经被完全加载上去。
replace: true
只是一个设置信息,告诉VUE本次操作后,不能通过浏览器后退按钮,返回前一个路由。确保用户在addRoutes()
还没有完成的时候,不可以点击浏览器回退按钮。
如果守卫中没有正确的放行出口的话,会一直next({ ...to})
进入死循环 。
实际应用
import router from './router'
const whiteList = ['/login','/whitePage'] //设置白名单
router.beforeEach((to, from, next) => {
const token = sessionStorage.getItem('access_token') // 获取token
// 存在 token 说明已经登录
if (token) {
// 登录过就不能访问登录界面,需要中断这一次路由守卫,执行下一次路由守卫,并且下一次守卫的to是主页'
if (to.path === '/login') {
next({ path: '/' })
}
// 保存在store中路由不为空则放行 (如果执行了刷新操作,则 store 里的路由为空,此时需要重新添加路由)
if (store.getters.getRoutes.length || to.name != null) {
//放行
next()
} else {
// 将路由添加到 store 中,用来标记已添加动态路由
store.commit('ADD_ROUTER', '需要添加的路由')
router.addRoutes('需要添加的路由')
// 如果 addRoutes 并未完成,路由守卫会一层一层的执行执行,直到 addRoutes 完成,找到对应的路由
// replace属性为true的时候可以让链接在跳转的时候不会留下历史记录。
next({ ...to, replace: true })
}
} else{
//token不存在 未登录
if (whiteList.indexOf(to.path) !== -1) {
//在免登录白名单直接进入
next()
} else {
// 其他没有访问权限的页面将被重定向到登录页面
next(`/login?redirect=${to.path}`)
}
}