验证token route 跳转
MrYu 2020-10-22 Vue
介绍
验证 token route 跳转
# token route 跳转正确办法
router.beforeEach((to, from, next) => {
if (store.state.user.token) {
next()
} else {
// 这就是跳出循环的关键
if (to.path === '/login') {
next()
} else {
next({
path: '/login',
query: { redirect: to.fullPath }, // 将要跳转路由的path作为参数,传递到登录页面
})
}
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 关于 next()
next() 和 next(‘/‘)是不一样的。
next() 是不会再次触发 router.beforeEach
next(‘/') 会再次触发 router.beforeEach,这样 不加判断会无限循环 router.beforeEach
if (to.path === '/login') { next() } else { next({ path: '/login', query: { redirect: to.fullPath }, // 将要跳转路由的path作为参数,传递到登录页面 }) }1
2
3
4
5
6
7
8
