fix(router): simplify route guard logic and remove unnecessary next calls

This commit is contained in:
soybeanfe
2026-03-09 12:42:50 +08:00
parent 6fc6f1c9b3
commit 3c2cbb7488
2 changed files with 13 additions and 27 deletions

View File

@@ -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?.();
});
}

View File

@@ -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<RouteLocationRaw
return null;
}
function handleRouteSwitch(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) {
function handleRouteSwitch(to: RouteLocationNormalized, from: RouteLocationNormalized) {
// route with href
if (to.meta.href) {
window.open(to.meta.href, '_blank');
next({ path: from.fullPath, replace: true, query: from.query, hash: to.hash });
return;
return { path: from.fullPath, replace: true, query: from.query, hash: to.hash };
}
next();
}
function getRouteQueryOfLoginRoute(to: RouteLocationNormalized, routeHome: RouteKey) {