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

如何在Nuxt 3中禁用默认路由并配置自定义手动路由?

在Nuxt 3中实现手动路由(禁用默认目录路由)

请不要尝试说服我使用Nuxt默认的基于目录的路由,我只需要手动路由方案。

当前@nuxtjs/router的Vue Router 4支持问题自2022年5月30日起无更新,且在Nuxt 3中使用该模块会报错,因此只能自行实现手动路由。

需要完成两项核心操作:

  • 禁用默认路由
  • 设置自定义路由

在Nuxt 2.X中,我们可以通过修改createRoutes属性禁用默认路由:

if (!options.parsePages) {
  this.nuxt.hook('build:before', () => {
    this.nuxt.options.build.createRoutes = () => {
      return []
    }
  })
}

但Nuxt 3.X中已移除createRoutes属性,需要用新的方式实现。


一、禁用Nuxt 3的默认路由

如果仍保留pages模块,可通过内联模块的pages:extend钩子清空默认生成的路由:

import { defineNuxtConfig } from "nuxt/config";

export default defineNuxtConfig({
  modules: [
    async (_, nuxt) => {
      nuxt.hook('pages:extend', (routes) => {
        routes.splice(0, routes.length)
      })
    }
  ]
});

若要彻底禁用自动路由生成,可直接关闭pages模块:

import { defineNuxtConfig } from "nuxt/config";

export default defineNuxtConfig({
  pages: false
});

二、设置自定义路由

通过创建Vue Router实例并注册为Nuxt插件来实现自定义路由:

  1. 创建plugins/router.ts文件,定义路由规则:
import { createRouter, createMemoryHistory, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('~/pages/home.vue')
  },
  {
    path: '/about',
    component: () => import('~/pages/about.vue')
  }
  // 添加更多自定义路由
]

export default defineNuxtPlugin(() => {
  const router = createRouter({
    // 根据服务端/客户端环境选择路由模式
    history: process.server ? createMemoryHistory() : createWebHistory(),
    routes
  })

  return {
    hooks: {
      'app:created': (app) => {
        app.use(router)
      }
    }
  }
})
  1. 在nuxt.config.ts中注册该插件:
import { defineNuxtConfig } from "nuxt/config";

export default defineNuxtConfig({
  pages: false,
  plugins: ['~/plugins/router.ts']
});

内容的提问来源于stack exchange,提问作者Takeshi Tokugawa YD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:40:27