vue3动态路由刷新出现空白页的原因与最优解
作者:二月如若微风
页面刷新白屏其实是因为vuex引起的,由于刷新页面vuex数据会丢失,这篇文章主要给大家介绍了关于vue3动态路由刷新出现空白页的原因与最优解的相关资料,需要的朋友可以参考下
动态路由刷新出现空白页:
原因:刷新页面的时候动态路由会刷新掉,然后动态路由会重新加载,而匹配路由会在加载路由之前,所以会导致空白页
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 }
总结
到此这篇关于vue3动态路由刷新出现空白页的原因与最优解的文章就介绍到这了,更多相关vue3动态路由刷新空白页内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!