docs: add 'going further' section for custom routing (#19565)

This commit is contained in:
Adrien Zaganelli 2023-03-15 15:16:03 +01:00 committed by GitHub
parent e383d06bf5
commit c56c9c6d7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 150 additions and 120 deletions

View File

@ -15,7 +15,7 @@ This directory is **optional**, meaning that [`vue-router`](https://router.vuejs
## Usage
Pages are Vue components and can have the `.vue`, `.js`, `.jsx`, `.ts` or `.tsx` extension.
Pages are Vue components and can have any [valid extension](https://nuxt.com/docs/api/configuration/nuxt-config#extensions) that Nuxt supports (by default `.vue`, `.js`, `.jsx`, `.mjs`, `.ts` or `.tsx`). Nuxt will automatically create a route for every page in your `~/pages/` directory.
::code-group
@ -333,125 +333,6 @@ A simple link to the `index.vue` page in your `pages` folder:
Learn more about [`<NuxtLink>`](/docs/api/components/nuxt-link) usage.
::
## Router Options
It is possible to customize [vue-router options](https://router.vuejs.org/api/interfaces/routeroptions.html).
### Using `app/router.options`
This is the recommended way to specify router options.
```js [app/router.options.ts]
import type { RouterConfig } from '@nuxt/schema'
// https://router.vuejs.org/api/interfaces/routeroptions.html
export default <RouterConfig> {
}
```
#### Custom Routes
You can optionally override routes using a function that accepts scanned routes and returns customized routes.
If returning `null` or `undefined`, Nuxt will fallback to the default routes. (useful to modify input array)
```js [app/router.options.ts]
import type { RouterConfig } from '@nuxt/schema'
// https://router.vuejs.org/api/interfaces/routeroptions.html
export default <RouterConfig> {
routes: (_routes) => [
{
name: 'home',
path: '/',
component: () => import('~/pages/home.vue')
}
],
}
```
::alert
Nuxt will not augment any new routes you return from the `routes` function with metadata defined in `definePageMeta` of the component you provide. If you want that to happen, you should probably use the `pages:extend` hook which is [called at build-time](/docs/api/advanced/hooks#nuxt-hooks-build-time).
::
#### Custom History (advanced)
You can optionally override history mode using a function that accepts base url and returns history mode.
If returning `null` or `undefined`, Nuxt will fallback to the default history.
```js [app/router.options.ts]
import type { RouterConfig } from '@nuxt/schema'
import { createMemoryHistory } from 'vue-router'
// https://router.vuejs.org/api/interfaces/routeroptions.html
export default <RouterConfig> {
history: base => process.client ? createMemoryHistory(base) : null /* default */
}
```
### Using `nuxt.config`
**Note:** Only JSON serializable options are configurable:
- `linkActiveClass`
- `linkExactActiveClass`
- `end`
- `sensitive`
- `strict`
- `hashMode`
```js [nuxt.config]
export default defineNuxtConfig({
router: {
// https://router.vuejs.org/api/interfaces/routeroptions.html
options: {}
}
})
```
### Hash Mode (SPA)
You can enable hash history in SPA mode. In this mode, router uses a hash character (#) before the actual URL that is internally passed. When enabled, the **URL is never sent to the server** and **SSR is not supported**.
```ts [nuxt.config.ts]
export default defineNuxtConfig({
ssr: false,
router: {
options: {
hashMode: true
}
}
})
```
## Modifying or Removing Scanned Pages
Nuxt will create a route for all files ending with one of the `extensions` configured in `nuxt.config`. (By default these are `.js`, `.jsx`, `.mjs`, `.ts`, `.tsx` and `.vue`.)
You can change or remove pages from the scanned routes with the `pages:extend` nuxt hook. For example, to prevent creating routes for any `.ts` files:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
hooks: {
'pages:extend' (pages) {
function removePagesMatching (pattern: RegExp, pages: NuxtPage[] = []) {
const pagesToRemove = []
for (const page of pages) {
if (pattern.test(page.file)) {
pagesToRemove.push(page)
} else {
removePagesMatching(pattern, page.children)
}
}
for (const page of pagesToRemove) {
pages.splice(pages.indexOf(page), 1)
}
}
removePagesMatching(/\.ts$/, pages)
}
}
})
```
## Programmatic Navigation
Nuxt 3 allows programmatic navigation through the `navigateTo()` utility method. Using this utility method, you will be able to programmatically navigate the user in your app. This is great for taking input from the user and navigating them dynamically throughout your application. In this example, we have a simple method called `navigate()` that gets called when the user submits a search form.
@ -475,3 +356,9 @@ function navigate(){
}
</script>
```
## Custom routing
As your app gets bigger and more complex, your routing might require more flexibility. For this reason, Nuxt directly exposes the router, routes and router options for customization in different ways.
:ReadMore{link="/docs/guide/going-further/custom-router"}

View File

@ -0,0 +1,143 @@
---
title: "Custom routing"
description: "In Nuxt 3, your routing is defined by the structure of your files inside the pages directory. However, since it uses vue-router under the hood, Nuxt offers you several ways to add custom routes in your project."
---
## Adding custom routes
In Nuxt 3, your routing is defined by the structure of your files inside the [pages directory](/docs/guide/directory-structure/pages). However, since it uses [vue-router](https://router.vuejs.org/) under the hood, Nuxt offers you several ways to add custom routes in your project.
### Using router config
Using [router options](/docs/2.guide/3.going-further/12.custom-router#router-options), you can optionally override or extend your routes using a function that accepts the scanned routes and returns customized routes.
If it returns `null` or `undefined`, Nuxt will fall back to the default routes (useful to modify input array).
```js [app/router.options.ts]
import type { RouterConfig } from '@nuxt/schema'
// https://router.vuejs.org/api/interfaces/routeroptions.html
export default <RouterConfig> {
routes: (_routes) => [
{
name: 'home',
path: '/',
component: () => import('~/pages/home.vue')
}
],
}
```
::alert
Nuxt will not augment any new routes you return from the `routes` function with metadata defined in `definePageMeta` of the component you provide. If you want that to happen, you should use the `pages:extend` hook which is [called at build-time](/docs/api/advanced/hooks#nuxt-hooks-build-time).
::
### Using the `pages:extend` hook
You can add, change or remove pages from the scanned routes with the `pages:extend` nuxt hook. For example, to prevent creating routes for any `.ts` files:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
hooks: {
'pages:extend' (pages) {
// add a route
pages.push({
name: 'profile',
path: '/profile',
component: () => import('~/pages/profile.vue')
})
// remove routes
function removePagesMatching (pattern: RegExp, pages: NuxtPage[] = []) {
const pagesToRemove = []
for (const page of pages) {
if (pattern.test(page.file)) {
pagesToRemove.push(page)
} else {
removePagesMatching(pattern, page.children)
}
}
for (const page of pagesToRemove) {
pages.splice(pages.indexOf(page), 1)
}
}
removePagesMatching(/\.ts$/, pages)
}
}
})
```
### Using a module
If you plan to add a whole set of pages related with a specific functionality, you might want to use a [Nuxt module](/modules).
The [Nuxt kit](docs/guide/going-further/kit) provides a few ways [to add routes](/docs/api/advanced/kit#pages):
- extendPages (callback: pages => void)
- extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions)
## Router Options
It is possible to customize [vue-router options](https://router.vuejs.org/api/interfaces/routeroptions.html).
### Using `app/router.options`
It is possible to customize [vue-router options](https://router.vuejs.org/api/interfaces/routeroptions.html).
This is the recommended way to specify router options.
```js [app/router.options.ts]
import type { RouterConfig } from '@nuxt/schema'
// https://router.vuejs.org/api/interfaces/routeroptions.html
export default <RouterConfig> {
}
```
### Using `nuxt.config`
**Note:** Only JSON serializable options are configurable:
- `linkActiveClass`
- `linkExactActiveClass`
- `end`
- `sensitive`
- `strict`
- `hashMode`
```js [nuxt.config]
export default defineNuxtConfig({
router: {
// https://router.vuejs.org/api/interfaces/routeroptions.html
options: {}
}
})
```
### Hash Mode (SPA)
You can enable hash history in SPA mode. In this mode, router uses a hash character (#) before the actual URL that is internally passed. When enabled, the **URL is never sent to the server** and **SSR is not supported**.
```ts [nuxt.config.ts]
export default defineNuxtConfig({
ssr: false,
router: {
options: {
hashMode: true
}
}
})
```
#### Custom History (advanced)
You can optionally override history mode using a function that accepts the base URL and returns the history mode. If it returns `null` or `undefined`, Nuxt will fallback to the default history.
```js [app/router.options.ts]
import type { RouterConfig } from '@nuxt/schema'
import { createMemoryHistory } from 'vue-router'
// https://router.vuejs.org/api/interfaces/routeroptions.html
export default <RouterConfig> {
history: base => process.client ? createMemoryHistory(base) : null /* default */
}
```