我的问题是,当我开始使用router.beforeEach()
时,当我键入不存在的链接时,他不会进入404页。他只是使用我使用的默认布局转到页面。我使用router.beforeEach()
来检查用户是否登录。是否缺少某些东西,或者有什么问题?
这是我的router.js
let router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'login',
component: () => import('./views/Login.vue'),
meta: {
layout: "empty"
},
},
{
path: '/home',
name: 'home',
component: () => import('./views/Home.vue'),
meta: {
requiresAuth: true
}
},
{
path: '/404',
name: '404',
component: () => import('./views/404.vue'),
meta: {
layout: "empty"
},
},
{
path: '*',
redirect: '/404'
},
{
path: '/*',
redirect: '/404'
}
]
});
router.beforeEach((to, from, next) => {
const isLoggedIn = JSON.parse(localStorage.getItem('UH'));
console.log(isLoggedIn);
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (isLoggedIn === null){
if (requiresAuth && !isLoggedIn.user) {
next('/');
} else {
next();
}
} else {
next();
}
});
答案 0 :(得分:0)
如果我很了解您的问题,当用户在网址中键入错误且未登录时,该用户将重定向到“ /”,而不是404。
这是因为在页面重定向{path: '*', redirect: '/404'}
之前使用了beforeEach挂钩,并且如果页面requireAuth为true,则您将重定向未登录用户的条件。
要解决此问题,请添加其他条件,如下所示:
if (isLoggedIn === null){
if (requiresAuth && !isLoggedIn.user) {
if (!to.matched.length) {
next('/404');
} else {
next('/');
}
} else {
next();
}
} else {
next();
}