動(dòng)態(tài)路由刷新出現(xiàn)空白頁(yè):
原因:刷新頁(yè)面的時(shí)候動(dòng)態(tài)路由會(huì)刷新掉,然后動(dòng)態(tài)路由會(huì)重新加載,而匹配路由會(huì)在加載路由之前,所以會(huì)導(dǎo)致空白頁(yè)文章來(lái)源:http://www.zghlxwxcb.cn/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; //默認(rèn)是false,刷新頁(yè)面這個(gè)也是false
let menuList=store.getters.GET_MENULIST; //后端返回的菜單列表
if (token) {
if(!hasRoutes){
bindRoute(menuList);//添加動(dòng)態(tài)路由
store.commit("SET_ROUTES_STATE",true);
}
next();
} else {
if (whiteList.includes(to.path)) {
next();
} else {
next('/login');
}
}
})
//添加動(dòng)態(tài)路由
const bindRoute = (menuList) => {
let newRoutes = router.options.routes;
menuList.forEach(menu => {
if (menu.children) {
menu.children.forEach(m => {
// 菜單轉(zhuǎn)成路由
let route = menuToRoute(m, menu.name);
if (route) {
newRoutes[0].children.push(route); // 添加到路由管理
}
})
}
})
// 重新添加到路由
newRoutes.forEach(route => {
router.addRoute(route)
})
}
// 菜單轉(zhuǎn)成路由
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
}
解決辦法:遞歸再調(diào)用beforEach,或者直接跳回首頁(yè)
在你加載路由的地方
遞歸調(diào)用:next({ …to, replace: true });(慎用,如果你的后臺(tái)管理table是帶標(biāo)簽會(huì)有問(wèn)題,沒(méi)有放對(duì)位置會(huì)死循環(huán))
跳回首頁(yè):next({path:‘/index’})
附上解決的代碼:文章來(lái)源地址http://www.zghlxwxcb.cn/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');
}
}
})
//添加動(dòng)態(tài)路由
const bindRoute = (menuList) => {
let newRoutes = router.options.routes;
menuList.forEach(menu => {
if (menu.children) {
menu.children.forEach(m => {
// 菜單轉(zhuǎn)成路由
let route = menuToRoute(m, menu.name);
if (route) {
newRoutes[0].children.push(route); // 添加到路由管理
}
})
}
})
// 重新添加到路由
newRoutes.forEach(route => {
router.addRoute(route)
})
}
// 菜單轉(zhuǎn)成路由
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
}
到了這里,關(guān)于vue3 關(guān)于動(dòng)態(tài)路由刷新出現(xiàn)空白頁(yè)最優(yōu)解的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!