From 3c2cbb748842e477ec1a9c19756a5bba6b07d67c Mon Sep 17 00:00:00 2001 From: soybeanfe Date: Mon, 9 Mar 2026 12:42:50 +0800 Subject: [PATCH] fix(router): simplify route guard logic and remove unnecessary next calls --- src/router/guard/progress.ts | 6 +++--- src/router/guard/route.ts | 34 ++++++++++------------------------ 2 files changed, 13 insertions(+), 27 deletions(-) diff --git a/src/router/guard/progress.ts b/src/router/guard/progress.ts index a1d4aee9..fee2e04f 100644 --- a/src/router/guard/progress.ts +++ b/src/router/guard/progress.ts @@ -1,11 +1,11 @@ import type { Router } from 'vue-router'; export function createProgressGuard(router: Router) { - router.beforeEach((_to, _from, next) => { + router.beforeEach(() => { window.NProgress?.start?.(); - next(); + return; }); - router.afterEach(_to => { + router.afterEach(() => { window.NProgress?.done?.(); }); } diff --git a/src/router/guard/route.ts b/src/router/guard/route.ts index 1a36989c..61626be4 100644 --- a/src/router/guard/route.ts +++ b/src/router/guard/route.ts @@ -1,10 +1,4 @@ -import type { - LocationQueryRaw, - NavigationGuardNext, - RouteLocationNormalized, - RouteLocationRaw, - Router -} from 'vue-router'; +import type { LocationQueryRaw, RouteLocationNormalized, RouteLocationRaw, Router } from 'vue-router'; import type { RouteKey, RoutePath } from '@elegant-router/types'; import { useAuthStore } from '@/store/modules/auth'; import { useRouteStore } from '@/store/modules/route'; @@ -17,12 +11,11 @@ import { getRouteName } from '@/router/elegant/transform'; * @param router router instance */ export function createRouteGuard(router: Router) { - router.beforeEach(async (to, from, next) => { + router.beforeEach(async (to, from) => { const location = await initRoute(to); if (location) { - next(location); - return; + return location; } const authStore = useAuthStore(); @@ -40,30 +33,27 @@ export function createRouteGuard(router: Router) { // if it is login route when logged in, then switch to the root page if (to.name === loginRoute && isLogin) { - next({ name: rootRoute }); - return; + return { name: rootRoute }; } // if the route does not need login, then it is allowed to access directly if (!needLogin) { - handleRouteSwitch(to, from, next); + handleRouteSwitch(to, from); return; } // the route need login but the user is not logged in, then switch to the login page if (!isLogin) { - next({ name: loginRoute, query: { redirect: to.fullPath } }); - return; + return { name: loginRoute, query: { redirect: to.fullPath } }; } // if the user is logged in but does not have authorization, then switch to the 403 page if (!hasAuth) { - next({ name: noAuthorizationRoute }); - return; + return { name: noAuthorizationRoute }; } // switch route normally - handleRouteSwitch(to, from, next); + handleRouteSwitch(to, from); }); } @@ -161,17 +151,13 @@ async function initRoute(to: RouteLocationNormalized): Promise