You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt3自定义路由引发vue-router及<nuxt-link>失效问题求助

Nuxt3 路由优先级问题解决

问题1:app/router.options.ts 配置导致页面崩溃

直接创建app/router.options.ts时,若完全替换路由数组而未保留Nuxt自动生成的内置路由(如Vite客户端路径、Nuxt基础路由),就会出现无法匹配/@vite/client这类必要路径的情况,进而引发页面崩溃、<nuxt-link>无法渲染的问题。

正确配置方式

需基于原有路由进行扩展,仅调整路由顺序而非完全替换:

import type { RouterConfig } from '@nuxt/schema'

export default <RouterConfig>{
  routes: (routes) => {
    // 定位目标路由
    const testRoute = routes.find(r => r.path === '/test-directory/test')
    const slugRoute = routes.find(r => r.path === '/test-directory/:slug')

    if (testRoute && slugRoute) {
      // 将test路由移至slug路由之前
      const testIndex = routes.indexOf(testRoute)
      const slugIndex = routes.indexOf(slugRoute)
      
      routes.splice(testIndex, 1)
      routes.splice(slugIndex, 0, testRoute)
    }

    return routes
  }
}

问题2:pages:extend 钩子点击链接仍匹配[slug].vue

点击链接时匹配错误的核心原因是路由顺序未正确调整,加上Nuxt缓存可能导致新配置未生效。

正确配置方式

在nuxt.config.ts的pages:extend钩子中,确保test.vue对应的路由项排在[slug].vue之前:

export default defineNuxtConfig({
  hooks: {
    'pages:extend'(pages) {
      const testPage = pages.find(p => p.path === '/test-directory/test')
      const slugPage = pages.find(p => p.path === '/test-directory/:slug')

      if (testPage && slugPage) {
        // 调整路由顺序,让test页面路由优先匹配
        pages.splice(pages.indexOf(testPage), 1)
        pages.splice(pages.indexOf(slugPage), 0, testPage)
      }
    }
  }
})

额外注意事项

调整完成后需:

  • 删除.nuxt文件夹和node_modules/.cache目录,清除Nuxt缓存
  • 重新启动开发服务器,确保新路由配置完全生效

调整后,客户端导航时会优先匹配/test-directory/test路径,点击链接和刷新页面都会正确指向test.vue。

内容的提问来源于stack exchange,提问作者J. Jackson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:47:32