路由兜底

This commit is contained in:
2026-06-06 15:30:09 +08:00
parent 5363613a7d
commit 495fde42ca
2 changed files with 38 additions and 12 deletions

View File

@@ -34,6 +34,23 @@ export const router = createRouter({
history: createWebHashHistory(),
routes: staticRoutes,
});
const hasValidResolvedRoute = (to: any) => {
const resolved = router.resolve(to.fullPath);
const matched = resolved.matched || [];
const isStaticFallbackRoute = matched.length === 1 && matched[0]?.path === '/:pathMatch(.*)*';
const isRedirectTo404Route = matched.length > 0 && matched.every((item) => item.redirect === '/404');
return matched.length > 0 && !isStaticFallbackRoute && !isRedirectTo404Route;
};
const goResolvedOr404AfterInit = (to: any, next: any) => {
if (hasValidResolvedRoute(to)) {
next({ ...to, replace: true });
} else {
next('/404');
}
};
/**
* 路由多级嵌套数组处理成一维数组
@@ -106,18 +123,18 @@ router.beforeEach(async (to, from, next) => {
const { routesList } = storeToRefs(storesRoutesList);
if (routesList.value.length === 0) {
if (isRequestRoutes) {
// 后端控制路由:路由数据初始化,防止刷新时丢失
await initBackEndControlRoutes();
// 动态添加路由:防止非首页刷新时跳转回首页的问题
// 确保 addRoute() 时动态添加的路由已经被完全加载上去
next({ ...to, replace: true });
goResolvedOr404AfterInit(to, next);
} else {
// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
await initFrontEndControlRoutes();
next({ ...to, replace: true });
goResolvedOr404AfterInit(to, next);
}
} else {
next();
if (hasValidResolvedRoute(to)) {
next();
} else {
next('/404');
}
}
}
}