布局
Nuxt Kit 提供一组实用工具,帮助你处理布局。
Layouts is used to be a wrapper around your pages. It can be used to wrap your pages with common components, for example, a header and a footer. Layouts can be registered using addLayout
utility.
addLayout
Register template as layout and add it to the layouts.
In Nuxt 2
error
layout can also be registered using this utility. In Nuxt 3+ error
layout replaced with error.vue
page in project root.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
Parameters
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:
属性 | 类型 | 必选 | 描述 |
---|---|---|---|
src | string | false | 模板的路径。如果未提供 src ,则必须提供 getContents 。 |
filename | string | false | 模板的文件名。如果未提供 filename ,则会从 src 路径生成。在这种情况下,必须提供 src 选项。 |
dst | string | false | 目标文件的路径。如果未提供 dst ,则会根据 filename 路径和 nuxt buildDir 选项生成。 |
options | Record<string, any> | false | 传递给模板的选项。 |
getContents | (data) => string | Promise<string> | false | 一个会使用 options 对象调用的函数。它应返回一个字符串或解析为字符串的 Promise。如果提供了 src ,则会忽略此函数。 |
write | boolean | false | 如果设置为 true ,模板将被写入目标文件。否则,模板仅在虚拟文件系统中使用。 |
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:
app/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
.