您的位置:首页 > Web前端 > Vue.js

使用vue-router beforeEach钩子遇到的一些小问题

2019-06-14 11:06 826 查看

一、从一个页面跳转到另一个页面时,如果用户未登录,需要跳转到登录页

此时全局路由拦截代码如下:

// 全局路由导航拦截
router.beforeEach((to, from, next) => {
// ...
let token = sessionStorage.getItem('userToken') // 获取用户登录token
if (token === null || token === '') { // 如果token不存在或者为空
next({ path: '/login' }) // 则跳转到登录页
}
})

当你点击路由进行跳转的时候,会发现报错了,如下图:

问题在于需要排除 此时地址 = 转向地址的情况,避免deep loop,解决方法如下:

// 全局路由导航拦截
router.beforeEach((to, from, next) => {
// ...
if (to.path === '/login') { // 如果是登录页面路径,就直接next()
next()
} else { // 其他页面路径
let token = sessionStorage.getItem('userToken') // 获取用户登录token
if (token === null || token === '') { // 如果token不存在或者为空
next({ path: '/login' }) // 则跳转到登录页
}
}
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: