Nuxt module to use router.js instead of pages/ directory
Use your own router.js
to handle your routes into your Nuxt.js application.
- Add
@nuxtjs/router
dependency to your project
yarn add @nuxtjs/router # or npm install @nuxtjs/router
- Add
@nuxtjs/router
to themodules
section ofnuxt.config.js
{
modules: [
// Simple usage
'@nuxtjs/router',
// With options
['@nuxtjs/router', { /* module options */ }]
]
}
{
modules: [
'@nuxtjs/router'
],
routerModule: {
/* module options */
}
}
If you are using SPA mode, add an index /
route to generate
section of nuxt.config.js
:
{
generate: {
routes: [
'/'
]
}
}
- Default:
srcDir
Location of you route file.
- Default:
router.js
Name of you route file.
- Default:
false
Can access the default router.
This module disable the pages/
directory into Nuxt and will use a router.js
file at your srcDir
directory:
components/
my-page.vue
router.js
router.js
need to export a createRouter
method like this:
import Vue from 'vue'
import Router from 'vue-router'
import MyPage from '~/components/my-page'
Vue.use(Router)
export function createRouter() {
return new Router({
mode: 'history',
routes: [
{
path: '/',
component: MyPage
}
]
})
}
If you use the module with { keepDefaultRouter: true }
, you can access the default router:
export function createRouter(ssrContext, createDefaultRouter) {
const defaultRouter = createDefaultRouter(ssrContext)
return new Router({
...defaultRouter.options,
routes: fixRoutes(defaultRouter.options.routes)
})
}
function fixRoutes(defaultRoutes) {
// default routes that come from `pages/`
return defaultRoutes.filter(...).map(...)
}
Copyright (c) Nuxt Community