页面

Nuxt Kit 提供了一组实用程序来帮助你创建和使用页面。你可以使用这些实用程序操作页面配置或定义路由规则。

extendPages

在 Nuxt 中,路由会根据 pages 目录中文件的结构自动生成。然而,在某些情况下,你可能需要自定义这些路由。例如,你可能需要为非 Nuxt 生成的动态页面添加路由、删除现有路由或修改路由配置。对于 extendPages 路由, 的优先级将高于 。

¥In Nuxt, routes are automatically generated based on the structure of the files in the pages directory. However, there may be scenarios where you'd want to customize these routes. For instance, you might need to add a route for a dynamic page not generated by Nuxt, remove an existing route, or modify the configuration of a route. For such customizations, Nuxt offers the extendPages feature, which allows you to extend and alter the pages configuration.

观看 Vue School 的视频,了解如何扩展页面。¥Watch Vue School video about extendPages.

类型

¥Type

function extendPages (callback: (pages: NuxtPage[]) => void): void

type NuxtPage = {
  name?: string
  path: string
  file?: string
  meta?: Record<string, any>
  alias?: string[] | string
  redirect?: RouteLocationRaw
  children?: NuxtPage[]
}

参数

¥Parameters

callback

类型:(pages: NuxtPage[]) => void

¥Type: (pages: NuxtPage[]) => void

必需:true

¥Required: true

一个函数,用于页面配置调用。你可以通过添加、删除或修改其元素来更改此数组。注意:你应该直接修改提供的 pages 数组,因为对复制的数组所做的更改不会反映在配置中。

¥A function that will be called with the pages configuration. You can alter this array by adding, deleting, or modifying its elements. Note: You should modify the provided pages array directly, as changes made to a copied array will not be reflected in the configuration.

示例

¥Examples

// https://github.com/nuxt-modules/prismic/blob/master/src/module.ts
import { createResolver, defineNuxtModule, extendPages } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options) {
    const resolver = createResolver(import.meta.url)

    extendPages((pages) => {
      pages.unshift({
        name: 'prismic-preview',
        path: '/preview',
        file: resolver.resolve('runtime/preview.vue')
       })
    })
  }
})

extendRouteRules

Nuxt 由 Nitro 服务器引擎提供支持。使用 Nitro,你可以将高级逻辑直接合并到配置中,这对于重定向、代理、缓存以及将标头附加到路由等操作非常有用。此配置通过将路由模式与特定的路由设置关联起来来实现。

¥Nuxt is powered by the Nitro server engine. With Nitro, you can incorporate high-level logic directly into your configuration, which is useful for actions like redirects, proxying, caching, and appending headers to routes. This configuration works by associating route patterns with specific route settings.

你可以在 Nitro documentation 中阅读有关 Nitro 路由规则的更多信息。
观看 Vue School 的视频,了解如何添加路由规则和路由中间件。¥Watch Vue School video about adding route rules and route middelwares.

类型

¥Type

function extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions): void

interface NitroRouteConfig {
  cache?: CacheOptions | false;
  headers?: Record<string, string>;
  redirect?: string | { to: string; statusCode?: HTTPStatusCode };
  prerender?: boolean;
  proxy?: string | ({ to: string } & ProxyOptions);
  isr?: number | boolean;
  cors?: boolean;
  swr?: boolean | number;
  static?: boolean | number;
}

interface ExtendRouteRulesOptions {
  override?: boolean
}

interface CacheOptions {
  swr?: boolean
  name?: string
  group?: string
  integrity?: any
  maxAge?: number
  staleMaxAge?: number
  base?: string
  headersOnly?: boolean
}

// See https://www.jsdocs.io/package/h3#ProxyOptions
interface ProxyOptions {
  headers?: RequestHeaders | HeadersInit;
  fetchOptions?: RequestInit & { duplex?: Duplex } & {
    ignoreResponseError?: boolean;
  };
  fetch?: typeof fetch;
  sendStream?: boolean;
  streamRequest?: boolean;
  cookieDomainRewrite?: string | Record<string, string>;
  cookiePathRewrite?: string | Record<string, string>;
  onResponse?: (event: H3Event, response: Response) => void;
}

参数

¥Parameters

route

类型:string

¥Type: string

必需:true

¥Required: true

要匹配的路由模式。

¥A route pattern to match against.

rule

类型:NitroRouteConfig

¥Type: NitroRouteConfig

必需:true

¥Required: true

应用于匹配路由的路由配置。

¥A route configuration to apply to the matched route.

options

类型:ExtendRouteRulesOptions

¥Type: ExtendRouteRulesOptions

默认:{}

¥Default: {}

传递给路由配置的选项。如果将 override 设置为 true,它将覆盖现有的路由配置。

¥Options to pass to the route configuration. If override is set to true, it will override the existing route configuration.

示例

¥Examples

// https://github.com/directus/website/blob/main/modules/redirects.ts
import { createResolver, defineNuxtModule, extendRouteRules, extendPages } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options) {
    const resolver = createResolver(import.meta.url)

    extendPages((pages) => {
      pages.unshift({
        name: 'preview-new',
        path: '/preview-new',
        file: resolver.resolve('runtime/preview.vue')
       })
    })

    extendRouteRules('/preview', {
      redirect: {
        to: '/preview-new',
        statusCode: 302
      }
    })

    extendRouteRules('/preview-new', {
      cache: {
        maxAge: 60 * 60 * 24 * 7
      }
    })
  }
})

addRouteMiddleware

注册路由中间件,使其可用于所有路由或特定路由。

¥Registers route middlewares to be available for all routes or for specific routes.

路由中间件也可以通过 addRouteMiddleware 可组合组件在插件中定义。

¥Route middlewares can be also defined in plugins via addRouteMiddleware composable.

了解更多关于 Route middleware documentation 中路由中间件的信息。
观看 Vue School 的视频,了解如何添加路由规则和路由中间件。¥Watch Vue School video about adding route rules and route middelwares.

类型

¥Type

function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions): void

type NuxtMiddleware = {
  name: string
  path: string
  global?: boolean
}

interface AddRouteMiddlewareOptions {
  override?: boolean
  prepend?: boolean
}

参数

¥Parameters

input

类型:NuxtMiddleware | NuxtMiddleware[]

¥Type: NuxtMiddleware | NuxtMiddleware[]

必需:true

¥Required: true

一个中间件对象或一个中间件对象数组,具有以下属性:

¥A middleware object or an array of middleware objects with the following properties:

  • name(必需)
    类型:string
    中间件名称。
  • path(必需)
    类型:string
    中间件的路径。
  • global(可选)
    类型:boolean
    如果启用,则将中间件注册为可用于所有路由。

options

类型:AddRouteMiddlewareOptions

¥Type: AddRouteMiddlewareOptions

默认:{}

¥Default: {}

  • override(可选)
    类型:boolean
    默认:false
    如果启用,将覆盖现有的同名中间件。
  • prepend(可选)
    类型:boolean
    默认:false
    如果启用,则将中间件添加到现有中间件列表的前面。

示例

¥Examples

export default defineNuxtRouteMiddleware((to, from) => {
  // isAuthenticated() is an example method verifying if a user is authenticated
  if (to.path !== '/login' && isAuthenticated() === false) {
    return navigateTo('/login')
  }
})