做项目的时候遇到了一个问题
vue在路由跳转的时候莫名其妙cpu爆满,网页直接卡死。而且地址栏跳转的路径也不对,代码如下
router.beforeEach((to, from, next) => {
const role = JSON.parse(localStorage.getItem("user"));
console.log(role);
if(to.fullPath === '/exit'){
localStorage.removeItem("user");
next({path: 'login'})
}else if(to.matched.length === 0){
next({
path: '404'
})
} else if (to.meta.requireAuth) {
if (store.state.user.username) {
if (to.meta.permission) {
// 如果是管理员权限则可进入
role.username === 'admin'
? next()
: next('403');
}
next()
} else {
ElMessage.error('请登录');
next({
path: 'login',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
}
后来经过很长时间的调试,发现整个循环判断执行了两次,且第二次要跳转的路由地址是直接把我/(反斜杠)后面的路径变成要跳转的路径了,
并没有变换整个路径
if(to.fullPath === '/exit'){
localStorage.removeItem("user");
next({path: 'login'})
}
解决办法:
在next中的path里面加上/(反斜杠)后再加要跳转的路径,代码如下
router.beforeEach((to, from, next) => {
const role = JSON.parse(localStorage.getItem("user"));
console.log(role);
if(to.fullPath === '/exit'){
localStorage.removeItem("user");
next({path: '/login'})
}else if(to.matched.length === 0){
next({
path: '/404'
})
} else if (to.meta.requireAuth) {
if (store.state.user.username) {
if (to.meta.permission) {
// 如果是管理员权限则可进入
role.username === 'admin'
? next()
: next('/403');
}
next()
} else {
ElMessage.error('请登录');
next({
path: '/login',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
}