问题描述
我在整合一个项目的前后台时候,后台的登录页面“http://localhost:8080/#/Manage_Login/”会自动跳转为”http://localhost:8080/#/Index“,然后我没有用路由的重定向,后来发现是router.beforeEach触发了两次,请问是为什么啊
问题出现的环境背景及自己尝试过哪些方法
相关代码
router.beforeEach((to, from, next) => {
var data = JSON.parse(localStorage.getItem('key'));
console.log('to', to,'from', from)
if (to.matched.some(r => r.meta.requireAuth)) {
if (data) {
next();
} else {
var state = localStorage.getItem('state');
//企业微信
if (state === 0) {
next({
path: '/ErrorPage/登录已失效,请重新登录!'
// query: {redirect: to.fullPath}
})
} else {
next({
path: '/Login',
query: {
redirect: to.fullPath
}
})
}
}
} else {
console.log(1)
next();
}
/* 路由发生变化修改页面title */
if (to.meta.title) {
document.title = to.meta.title
}
console.log(2)
// next()
})
确实是有这么个问题,这个需要看下源码理解下,这三个参数有顺序的。
出问题的代码如下:
看似是如果
user
为null
就跳转到'/login'
这个路由中去,但是 to, from, next 三个变量的执行顺序得明确下:首先路由会先到
to.path
然后检查
next.path
有没有值,如果没有,则不跳转,若有,向next.path
这个值跳转。现在这样一个情况出现了,假定 to.path == '/login',
在刚才代码的情况下, 路由首先跳到
/login
, 然后检查next
, 发现next
里面的 path 是 '/login', 不为空,那么就继续跳next.path
这个路由, 也就是'/login'
,这次跳的时候,to.path
就是又设置为'/login'
了, 那么就又回到开始的情况了,于是死循环。那么怎么避免这种情况发生呢,很简单,每次我们要改变跳转的时候,也就是要给next.path 赋值的时候,只要这个值与to.path的值相同,那么,就不要赋值了,赋值就死循环。
所以正确的代码如下: