动态路由刷新出现空白页:
原因:刷新页面的时候动态路由会刷新掉,然后动态路由会重新加载,而匹配路由会在加载路由之前,所以会导致空白页文章来源:https://www.toymoban.com/news/detail-610363.html
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’})
附上解决的代码:文章来源地址https://www.toymoban.com/news/detail-610363.html
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
}
到了这里,关于vue3 关于动态路由刷新出现空白页最优解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!