Лейаут

Исходники
Nuxt Kit предоставляет набор утилит, которые помогают вам работать с лейаутами.

Лейауты используются в качестве обертки вокруг ваших страниц. Они могут использоваться для оборачивания страниц общими компонентами, например, хедером и футером. Лейауты могут быть зарегистрированы с помощью утилиты addLayout.

addLayout

Зарегистрируйте шаблон как лейаут и добавьте его в лейауты.

В Nuxt 2 лейаут error также может быть зарегистрирован с помощью этой утилиты. В Nuxt 3+ лейаут errorзаменен на страницу error.vue в корне проекта.

Usage

import { addLayout, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup () {
    const { resolve } = createResolver(import.meta.url)

    addLayout({
      src: resolve('templates/custom-layout.ts'),
      filename: 'custom-layout.ts',
    }, 'custom')
  },
})

Type

function addLayout(layout: NuxtTemplate | string, name: string): void

Параметры

layout: A template object or a string with the path to the template. If a string is provided, it will be converted to a template object with src set to the string value. If a template object is provided, it must have the following properties:

PropertyTypeRequiredDescription
srcstringfalsePath to the template. If src is not provided, getContents must be provided instead.
filenamestringfalseFilename of the template. If filename is not provided, it will be generated from the src path. In this case, the src option is required.
dststringfalsePath to the destination file. If dst is not provided, it will be generated from the filename path and nuxt buildDir option.
optionsRecord<string, any>falseOptions to pass to the template.
getContents(data) => string | Promise<string>falseA function that will be called with the options object. It should return a string or a promise that resolves to a string. If src is provided, this function will be ignored.
writebooleanfalseIf set to true, the template will be written to the destination file. Otherwise, the template will be used only in virtual filesystem.

name: The name to register the layout under (e.g., default, custom, etc.).

Example

This will register a layout named custom that wraps pages with a header and footer.

import { addLayout, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup () {
    addLayout({
      write: true,
      filename: 'my-layout.vue',
      getContents: () => `<template>
  <div>
    <header>My Header</header>
    <slot />
    <footer>My Footer</footer>
  </div>
</template>`,
    }, 'custom')
  },
})

You can then use this layout in your pages:

pages/about.vue
<script setup lang="ts">
definePageMeta({
  layout: 'custom',
})
</script>

<template>
  <div>About Page</div>
</template>
Due to the lack of support for virtual .vue files by @vitejs/plugin-vue, you can work around this limitation by passing write: true to the first argument of addLayout.
Был ли материал полезен?