This commit is contained in:
zhoutianchi
2026-02-28 17:38:37 +08:00
parent 4a9350211d
commit 9e0407331a
9 changed files with 47 additions and 22 deletions

View File

@@ -5,6 +5,7 @@ import pinia from '/@/stores/index';
import { storeToRefs } from 'pinia';
import { useKeepALiveNames } from '/@/stores/keepAliveNames';
import { useRoutesList } from '/@/stores/routesList';
import { useUserInfo } from '/@/stores/userInfo';
import { Session } from '/@/utils/storage';
import { staticRoutes, notFoundAndNoPower } from '/@/router/route';
import { initBackEndControlRoutes } from '/@/router/backEnd';
@@ -91,6 +92,18 @@ export function formatTwoStageRoutes(arr: any) {
router.beforeEach(async (to, from, next) => {
NProgress.configure({ showSpinner: false });
if (to.name) NProgress.start();
// 全局监听 URL 参数 token若存在则写入缓存与登录成功同一方法不在此处 redirect避免先跳转再 init 导致 tagsView 首次丢失
const urlToken = to.query?.token as string | undefined;
if (urlToken) {
useUserInfo().setTokenCache(urlToken, to.query?.refresh_token as string | undefined);
}
// 若上面刚写了 token后续用去掉 token 的 query 做一次 replace在 init 之后统一做保证只一次导航、tagsView 能正确加 tag
const stripTokenQuery =
urlToken && to.query
? Object.fromEntries(Object.entries(to.query).filter(([k]) => k !== 'token' && k !== 'refresh_token'))
: null;
const token = Session.getToken();
if (to.meta.isAuth !== undefined && !to.meta.isAuth) {
next();
@@ -117,9 +130,16 @@ router.beforeEach(async (to, from, next) => {
if (routesList.value.length === 0) {
// 后端控制路由:路由数据初始化,防止刷新时丢失
await initBackEndControlRoutes();
next({ path: to.path, query: to.query });
// 只传 path/params/query让路由器用刚添加的动态路由重新解析避免沿用进入守卫时解析到的 404
const query = stripTokenQuery ?? to.query;
next({ path: to.path, params: to.params, query, replace: true });
} else {
next();
// 已有路由列表,若本次是带 token 的 URL做一次 replace 去掉地址栏 token
if (stripTokenQuery) {
next({ path: to.path, params: to.params, query: stripTokenQuery, replace: true });
} else {
next();
}
}
}
}