路由跳转逻辑bug修复

This commit is contained in:
2026-03-30 09:27:47 +08:00
parent b05d42cfc8
commit f208c3c744

View File

@@ -8,11 +8,8 @@ import { isRelogin } from '@/utils/request'
NProgress.configure({ showSpinner: false })
/**
* 从菜单树中查找 jumpFlag===1 的默认跳转路径
* 若打标在父节点则取其下第一个可见叶子路径;若在叶子则直接返回该路径
*/
function findDefaultPathFromMenus(menus) {
// 从菜单树中查找第一个可见叶子菜单路径(按接口返回顺序)
function findFirstLeafPathFromMenus(menus) {
if (!Array.isArray(menus) || menus.length === 0) return null
function dfs(list, parentPath = '') {
@@ -22,23 +19,34 @@ function findDefaultPathFromMenus(menus) {
const currentPath = rawPath.startsWith('/')
? rawPath
: `${parentPath}/${rawPath}`.replace(/\/+/g, '/')
if (item.jumpFlag === 1) {
if (item.children && item.children.length > 0) {
const childPath = dfs(item.children, currentPath)
return childPath != null ? childPath : currentPath
}
return currentPath
}
if (item.children && item.children.length > 0) {
const found = dfs(item.children, currentPath)
if (found != null) return found
} else {
return currentPath
}
}
return null
}
return dfs(menus)
}
function findFirstLeafPathFromRoutes(routes) {
if (!Array.isArray(routes) || routes.length === 0) return null
const stack = [...routes]
while (stack.length) {
const route = stack.shift()
if (!route || route.hidden === true) continue
if (Array.isArray(route.children) && route.children.length > 0) {
stack.unshift(...route.children)
continue
}
const p = route.path || ''
if (typeof p === 'string' && p.startsWith('/') && p !== '/404') {
return p
}
}
return null
}
// 增加三方登陆 update by 芋艿
const whiteList = ['/login', '/social-login', '/auth-redirect', '/bind', '/register', '/oauthLogin/gitee']
@@ -65,11 +73,16 @@ router.beforeEach((to, from, next) => {
store.dispatch('GenerateRoutes', userInfo.menus).then(accessRoutes => {
// 根据 roles 权限生成可访问的路由表
router.addRoutes(accessRoutes) // 动态添加可访问路由表
const defaultPath = findDefaultPathFromMenus(userInfo.menus) || '/'
const menuDefaultPath = findFirstLeafPathFromMenus(userInfo.menus)
const routeFallbackPath = findFirstLeafPathFromRoutes(accessRoutes)
const defaultPath = menuDefaultPath || routeFallbackPath || '/'
store.dispatch('SetDefaultPath', defaultPath)
// 仅当目标为根路径 '/' 时跳默认页;否则保持当前路径(含刷新场景),避免刷新被误判为“未匹配”而跳到默认页
if (to.path === '/') {
next({ path: defaultPath, replace: true })
const matched = router.match(defaultPath)
const hasMatch = matched && Array.isArray(matched.matched) && matched.matched.length > 0
const safePath = hasMatch ? defaultPath : (routeFallbackPath || '/')
next({ path: safePath, replace: true })
} else {
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成当前页刷新时保留 to 的路径
}