解决路由守卫的死循环
使用路由守卫时报错,错误描述:
RangeError: Maximum call stack size exceeded at Function.keys (<anonymous>) at eval (vue-router.esm.js?8c4f:2171:1)at Array.map (<anonymous>) at flatMapComponents (vue-router.esm.js ?8c4f:2170:1)at eval (vue-router.esm.js?8c4f: 2106:1) at iterator (vue-router.esm.js?8c4f: 2362:1)at step (vue-router.esm.js?8c4f : 2804:1) at step (vue-router.esm.js?8c4f: 2808:1)at eval ( vue-router.esm.is?8c4f:2005:1)
错误的意思是 “超出最大调用堆栈大小”,简单来说就是进入了死循环
代码:
(token && to.path=== Login {
已登录且要跳转的页面是登录页
next({ path: Login })
因为在进入每一个路由之前都会调用这个回调,进入登录界面会在判断后再次进入登录界面,因此产生了死循环
解决方法是:要给路径做一个判断,例子
router.beforeEach((to,from,next)=>{
console.log(to.path);
if(to.path==='/login'){
console.log(1)
next();
}else{
let user=localStorage.getItem('userInfo')?JSON.parse(localStorage.getItem('userInfo')):null;
if(user){
console.log(2)
next();
}else {
console.log(3)
next('/login');
}
}
console.log(4)
})
路由守卫
全局路由守卫
路径src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
//创建一个路由器
const router = new VueRouter({
routes:[
{
name:'guanyv',
path:'/about',
component:About,
meta:{title:'关于'}
},
{
name:'zhuye',
path:'/home',
component:Home,
meta:{title:'主页'},
children:[
{
name:'xinwen',
path:'news',
component:News,
meta:{isAuth:true,title:'新闻'}
},
{
name:'xiaoxi',
path:'message',
component:Message,
meta:{isAuth:true,title:'消息'},
children:[
{
name:'xiangqing',
path:'detail',
component:Detail,
meta:{isAuth:true,title:'详情'},
props($route){
return {
id:$route.query.id,
title:$route.query.title,
}
}
}
]
}
]
}
]
})
//全局前置路由守卫————初始化的时候、每次路由切换之前被调用
router.beforeEach((to,from,next) => {
console.log('前置路由守卫',to,from)
if(to.meta.isAuth){
if(localStorage.getItem('school')==='atguigu'){
next()
}else{
alert('学校名不对,无权限查看!')
}
}else{
next()
}
})
//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
console.log('后置路由守卫',to,from)
document.title = to.meta.title || '硅谷系统'
})
//导出路由器
export default router