vue路由跳转错误:Error: Redirected when going from "/login" to "/index" via a navigation guard.
login.vue
login(formName) {
let param = {
account: this.ruleForm.account,
password: this.ruleForm.password,
captcha: this.ruleForm.captcha
}
this.$refs[formName].validate((valid) => {
if (valid) {
api.login(param)
.then(res => {
if (res.code === 1) {
this.$message({
showClose: true,
message: res.message,
type: 'error'
});
} else {
this.$router.push({path: '/index'});
this.setToken(res.token);
}
})
} else {
return false;
}
});
router.js
router.beforeEach((to,from,next) => {
const token = cookie.get('Authorization');
if(to.matched.some(res=>res.meta.isLogin)) {//判断是否需要登录
if (token) {
next();
}else{
next({
path:"/login",
query: {redirect: to.fullPath}
});
}
}else{
next()
}
if(to.path == "/login"){
if(token){
next('/index');
} else {
next('/login');
}
}
});
出现错误:
分析:当我们第一次点击登录时出现以上错误,点击第二次登录时正在进入主页
更具login.vue的代码可知,是先出发的路由跳转再存token;这样就导致,第一次登录时在路由守卫中无法拿到token;先进行了页面的跳转,因此因此守卫路由中断当前的导航(本次跳转),抛出异常,无法进入首页,第二次登陆能够登入首页是因为第一次登陆已经放好了token,因此正常拿到token也就能正常走这个函数了
解决办法:先设置token在进行路由跳转
login(formName) {
let param = {
account: this.ruleForm.account,
password: this.ruleForm.password,
captcha: this.ruleForm.captcha
}
this.$refs[formName].validate((valid) => {
if (valid) {
api.login(param)
.then(res => {
if (res.code === 1) {
this.$message({
showClose: true,
message: res.message,
type: 'error'
});
} else {
this.setToken(res.token);
this.$router.push({path: '/index'});
}
})
} else {
return false;
}
});