路由兜底

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(), history: createWebHashHistory(),
routes: staticRoutes, 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); const { routesList } = storeToRefs(storesRoutesList);
if (routesList.value.length === 0) { if (routesList.value.length === 0) {
if (isRequestRoutes) { if (isRequestRoutes) {
// 后端控制路由:路由数据初始化,防止刷新时丢失
await initBackEndControlRoutes(); await initBackEndControlRoutes();
// 动态添加路由:防止非首页刷新时跳转回首页的问题 goResolvedOr404AfterInit(to, next);
// 确保 addRoute() 时动态添加的路由已经被完全加载上去
next({ ...to, replace: true });
} else { } else {
// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
await initFrontEndControlRoutes(); await initFrontEndControlRoutes();
next({ ...to, replace: true }); goResolvedOr404AfterInit(to, next);
} }
} else { } else {
next(); if (hasValidResolvedRoute(to)) {
next();
} else {
next('/404');
}
} }
} }
} }

View File

@@ -1,4 +1,4 @@
import { RouteRecordRaw } from 'vue-router'; import { RouteRecordRaw } from 'vue-router';
/** /**
* 路由meta对象参数说明 * 路由meta对象参数说明
@@ -1077,8 +1077,8 @@ export const demoRoutes: Array<RouteRecordRaw> = [
*/ */
export const notFoundAndNoPower = [ export const notFoundAndNoPower = [
{ {
path: '/:path(.*)*', path: '/404',
name: 'notFound', name: 'notFoundPage',
component: () => import('/@/views/error/404.vue'), component: () => import('/@/views/error/404.vue'),
meta: { meta: {
title: 'message.staticRoutes.notFound', title: 'message.staticRoutes.notFound',
@@ -1094,6 +1094,15 @@ export const notFoundAndNoPower = [
isHide: true, isHide: true,
}, },
}, },
{
path: '/:path(.*)*',
name: 'notFound',
redirect: '/404',
meta: {
title: 'message.staticRoutes.notFound',
isHide: true,
},
},
]; ];
/** /**