vue.js - vuejs - 如果已经登录,则从登录/注册重定向到主页,如果未在 vue-router 中登录,则从其他页面重定向到登录
问题描述
如果登录并想要访问登录/注册页面,我想将用户重定向到主页,如果未登录并想要访问其他页面,我想将用户重定向到登录页面。有些页面被排除在外,这意味着不需要登录,所以我的代码就在下面:
router.beforeEach((to, from, next) => {
if(
to.name == 'About' ||
to.name == 'ContactUs' ||
to.name == 'Terms'
)
{
next();
}
else
{
axios.get('/already-loggedin')
.then(response => {
// response.data is true or false
if(response.data)
{
if(to.name == 'Login' || to.name == 'Register')
{
next({name: 'Home'});
}
else
{
next();
}
}
else
{
next({name: 'Login'});
}
})
.catch(error => {
// console.log(error);
});
}
});
但问题是它进入了一个无限循环,例如每次登录页面加载而用户未登录时,它会将用户重定向到登录页面并再次重定向到登录页面......
我怎样才能解决这个问题?
解决方案
这就是我正在做的事情。首先我使用meta
路由数据,所以我不需要手动放置所有不需要登录的路由:
routes: [
{
name: 'About' // + path, component, etc
},
{
name: 'Dashboard', // + path, component, etc
meta: {
requiresAuth: true
}
}
]
然后,我有一个像这样的全局守卫:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!store.getters.isLoggedIn) {
next({ name: 'Login' })
} else {
next() // go to wherever I'm going
}
} else {
next() // does not require auth, make sure to always call next()!
}
})
在这里,我存储用户是否登录,而不是发出新请求。
在您的示例中,您忘记Login
将“不需要身份验证”的页面包含在列表中。因此,如果用户试图去让我们说Dashboard
,你提出请求,结果他没有登录。然后他去Login
,但你的代码检查,发现它不是 3“不需要身份验证”列表的一部分,并制作另一个电话:)
因此跳过这个“列表”是至关重要的!;)
祝你好运!
推荐阅读
- python - Python 3.x - 计算绘图&&计算坐标系中可能的正方形
- mysql - MySQL 在一次查询中选择 table_name、table_shema 和 table_id
- jasper-reports - jasper 报告 - msg 函数不接受超过 4 个参数,包括模式
- java - 具有多个子类的休眠映射并从最小子类获取超级父数据
- python - 如何通过 path() 函数在 url 中传递可选参数?
- python - Keras:添加类权重后损失巨大
- paramiko - [asyncssh]:使用 python asyncssh 反向 ssh 隧道
- bash - bash 子序列匹配加速
- javascript - 从锚标签href属性更改自定义词
- python - 如何使用 Python 遍历目录中的文件并在给定特定约束的情况下输出 pandas 数据框?