vue.js - 如何在 vue-router 中同时保护 '/login' 或 '/login/' 和 '/dashboard' 或 '/dashboard/'
问题描述
我正在使用 vue-router 在我的系统中设置路由保护,如果用户尝试在 URL 中输入 /login 或 /login/ 则将用户重定向回仪表板,反之亦然,如果他们没有令牌。
路由器.js
router.beforeEach((to, from, next) => {
if (to.fullPath === '/dashboard/') {
if (!store.state.authToken) {
next('/login');
}
}
if (to.fullPath === '/login/') {
if (store.state.accessToken) {
next('/dashboard');
}
}
next();
});
我的问题是,如果我输入 '/login' 或 '/dashboard' (最后没有反斜杠),它会绕过我的防护,所以我尝试 在我的代码中进行操作(to.fullPath === '/login/' || '/login')
,(to.fullPath === '/dashboard/' || '/dashboard')
这在 4 小时前就成功了。
然后我现在回来了,现在它给了我错误,说[vue-router] uncaught error during route navigation
每当我通过 URL 更改视图时。
我不知道它为什么停止工作,请帮忙。
谢谢!
编辑:我打错了,打电话给 accessToken 而不是 authToken 这就是警卫失败的原因。已修复,谢谢!
解决方案
您可以为您的路线命名并根据该名称进行重定向。
额外的更改可能是向您的路由添加一些元数据,无论该路由是否需要用户进行身份验证,从而使其更易于扩展,而无需在您的 beforeEach 中指定每个受保护的路由
路线
{
path: '/login',
name: 'login',
component: () => import('./views/Login.vue'),
meta: { requiresAuth: false }
},
{
path: '/dashboard',
name: 'dashboard',
component: () => import('./views/Dasboard.vue'),
meta: { requiresAuth: true }
}
警卫
router.beforeEach((to, from, next) => {
/* Both '/login' and '/login/' should share the same route name even if their path is different */
if (to.name === 'login') {
if (store.state.accessToken) {
next('/dashboard');
}
}
//Redirect to login if the route requires auth and no token is set
if(to.meta.requiresAuth) {
if (!store.state.accessToken) {
next('/login');
}
}
next();
});
推荐阅读
- calibre - 口径编辑的书内容未保存
- r - R – 如何为具有接近值的匹配数据提供一个通用 ID,并为配对测试安排数据帧(例如来自 Hmisc::find.matches() )
- reactjs - 离子反应中的反应挂钩(使用状态)错误
- sql - SQL - 按另一列的特定值分组的特定列的总和
- python - 当我有一个数据框时,为什么 Python 会告诉我 **TypeError: unhashable type: 'list'**?
- python - Webdriver不返回一些数据
- c# - CS0120 大型文件列表 C# Discord webhook
- wpf - WinForms/WPF 控件的全局唯一标识符?
- web3 - 使用 Web3 读取 LP 池的余额
- anaconda - Pytorch 在 conda 上安装失败,错误为 -CondaHTTPError: HTTP 403 FORBIDDEN for url