动态路由刷新出现空白页:
原因:刷新页面的时候动态路由会刷新掉,然后动态路由会重新加载,而匹配路由会在加载路由之前,所以会导致空白页
router.beforeEach(async (to, from, next)=>{const whiteList =['/login']
let token = store.getters.GET_TOKEN;//token
let hasRoutes=store.state.hasRoutes;//默认是false,刷新页面这个也是false
let menuList=store.getters.GET_MENULIST;//后端返回的菜单列表if(token){if(!hasRoutes){bindRoute(menuList);//添加动态路由
store.commit("SET_ROUTES_STATE",true);}next();}else{if(whiteList.includes(to.path)){next();}else{next('/login');}}})//添加动态路由const bindRoute =(menuList)=>{
let newRoutes = router.options.routes;
menuList.forEach(menu =>{if(menu.children){
menu.children.forEach(m =>{// 菜单转成路由
let route =menuToRoute(m, menu.name);if(route){
newRoutes[0].children.push(route);// 添加到路由管理}})}})// 重新添加到路由
newRoutes.forEach(route =>{
router.addRoute(route)})}// 菜单转成路由const menuToRoute =(menu, parentName)=>{
let route ={
name: menu.name,
path: menu.path,
meta:{
parentName: parentName
},
children:[],}if(!menu.component){
route.component = ''
}else{
route.component =()=>import('@/views/' + menu.component +'.vue')}return route
}
解决办法:递归再调用beforEach,或者直接跳回首页
在你加载路由的地方
递归调用:next({ …to, replace: true });(慎用,如果你的后台管理table是带标签会有问题,没有放对位置会死循环)
跳回首页:next({path:‘/index’})
附上解决的代码:
router.beforeEach(async (to, from, next)=>{const whiteList =['/login']
let token = store.getters.GET_TOKEN;
let hasRoutes=store.state.hasRoutes;
let menuList=store.getters.GET_MENULIST;if(token){
console.log(store.state.editabTabs)if(!hasRoutes){bindRoute(menuList);
store.commit("SET_ROUTES_STATE",true);//next({ ...to, replace: true });//----------解决next({path:'/index'});//----------解决}next();}else{if(whiteList.includes(to.path)){next();}else{next('/login');}}})//添加动态路由const bindRoute =(menuList)=>{
let newRoutes = router.options.routes;
menuList.forEach(menu =>{if(menu.children){
menu.children.forEach(m =>{// 菜单转成路由
let route =menuToRoute(m, menu.name);if(route){
newRoutes[0].children.push(route);// 添加到路由管理}})}})// 重新添加到路由
newRoutes.forEach(route =>{
router.addRoute(route)})}// 菜单转成路由const menuToRoute =(menu, parentName)=>{
let route ={
name: menu.name,
path: menu.path,
meta:{
parentName: parentName
},
children:[],}if(!menu.component){
route.component = ''
}else{
route.component =()=>import('@/views/' + menu.component +'.vue')}return route
}
版权归原作者 二月如若微风 所有, 如有侵权,请联系我们删除。