fix(router): resolve Vue Router warning for dynamic tool routes

- Improve route existence check using router.resolve() for accurate nested route detection
- Register tool routes before router is used to prevent 'No match found' warnings
- Update beforeEach guard to handle dynamic route registration more reliably
This commit is contained in:
jingrow 2025-11-22 00:26:56 +08:00
parent 994df7f237
commit 85058f51e7
2 changed files with 48 additions and 33 deletions

View File

@ -18,23 +18,20 @@ import '@fortawesome/fontawesome-free/css/all.min.css'
const app = createApp(App)
app.use(createPinia())
// 初始化认证状态需要在pinia初始化之后
import { useAuthStore } from '../shared/stores/auth'
const authStore = useAuthStore()
authStore.initAuth()
// 在路由使用前注册工具路由,避免路由匹配时的警告
import { useToolsStore } from '../shared/stores/tools'
const toolsStore = useToolsStore()
toolsStore.initToolRoutes(router)
app.use(router)
app.use(naive)
// 初始化fetch拦截器需要在pinia初始化之后
import '../shared/utils/fetchInterceptor'
// 初始化认证状态
import { useAuthStore } from '../shared/stores/auth'
const authStore = useAuthStore()
authStore.initAuth()
import { useToolsStore } from '../shared/stores/tools'
router.isReady().then(() => {
const toolsStore = useToolsStore()
toolsStore.initToolRoutes(router)
}).catch((error) => {
console.error('Failed to initialize tool routes:', error)
})
app.mount('#app')

View File

@ -205,27 +205,45 @@ router.beforeEach(async (to, _from, next) => {
}
if (to.path.startsWith('/tools/') && to.name !== 'Tools') {
const routeExists = to.matched.length > 0 || router.getRoutes().some(r => {
const fullPath = r.path.startsWith('/') ? r.path : `/${r.path}`
return fullPath === to.path
})
if (!routeExists) {
const { useToolsStore } = await import('../../shared/stores/tools')
const toolsStore = useToolsStore()
toolsStore.initToolRoutes(router)
// 如果路由已经匹配,直接通过
if (to.matched.length > 0) {
// 路由已匹配,继续正常流程
} else {
// 尝试解析路由,检查是否存在
let routeExists = false
try {
const resolved = router.resolve(to.path)
// 如果解析成功且路径匹配,说明路由存在
routeExists = resolved.matched.length > 0 && resolved.path === to.path
} catch {
// 解析失败,说明路由不存在
routeExists = false
}
const routeExistsAfter = router.getRoutes().some(r => {
const fullPath = r.path.startsWith('/') ? r.path : `/${r.path}`
return fullPath === to.path
})
if (routeExistsAfter) {
next({ ...to, replace: true })
return
} else {
next('/tools')
return
// 如果路由不存在,尝试初始化工具路由
if (!routeExists) {
const { useToolsStore } = await import('../../shared/stores/tools')
const toolsStore = useToolsStore()
toolsStore.initToolRoutes(router)
// 再次尝试解析路由
let routeExistsAfter = false
try {
const resolvedAfter = router.resolve(to.path)
routeExistsAfter = resolvedAfter.matched.length > 0 && resolvedAfter.path === to.path
} catch {
routeExistsAfter = false
}
if (routeExistsAfter) {
// 路由已注册,重新导航到目标路由
next({ ...to, replace: true })
return
} else {
// 路由不存在,重定向到工具列表页
next('/tools')
return
}
}
}
}