路由兜底

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');
}
}
}
}

View File

@@ -1,4 +1,4 @@
import { RouteRecordRaw } from 'vue-router';
import { RouteRecordRaw } from 'vue-router';
/**
* 路由meta对象参数说明
@@ -69,9 +69,9 @@ export const dynamicRoutes: Array<RouteRecordRaw> = [
/**
* 盘点管理路由配置(供后端菜单配置参考)
*
*
* 父级菜单: 库存作业 (/assets/operation)
*
*
* 盘点菜单配置:
* - 路由路径: /assets/operation/count
* - 组件路径: assets/operation/count/index
@@ -1077,8 +1077,8 @@ export const demoRoutes: Array<RouteRecordRaw> = [
*/
export const notFoundAndNoPower = [
{
path: '/:path(.*)*',
name: 'notFound',
path: '/404',
name: 'notFoundPage',
component: () => import('/@/views/error/404.vue'),
meta: {
title: 'message.staticRoutes.notFound',
@@ -1094,6 +1094,15 @@ export const notFoundAndNoPower = [
isHide: true,
},
},
{
path: '/:path(.*)*',
name: 'notFound',
redirect: '/404',
meta: {
title: 'message.staticRoutes.notFound',
isHide: true,
},
},
];
/**