<NuxtLayout>
Nuxt 提供了 <NuxtLayout> 组件用于在页面和错误页面上显示布局。
你可以使用 <NuxtLayout />
组件在 app.vue
或 error.vue
上激活 default
布局。
app.vue
<template>
<NuxtLayout>
some page content
</NuxtLayout>
</template>
Props
name
: 指定要渲染的布局名称,可以是字符串、响应式引用或计算属性。它 必须 与layouts/
目录中相应布局文件的名称匹配。- type:
string
- default:
default
- type:
pages/index.vue
<script setup lang="ts">
// layouts/custom.vue
const layout = 'custom'
</script>
<template>
<NuxtLayout :name="layout">
<NuxtPage />
</NuxtLayout>
</template>
请注意,布局名称会被标准化为 kebab-case,因此如果你的布局文件名为 errorLayout.vue
,当作为 name
属性传递给 <NuxtLayout />
时,它将变为 error-layout
。
error.vue
<template>
<NuxtLayout name="error-layout">
<NuxtPage />
</NuxtLayout>
</template>
fallback
: 如果传递给name
属性的布局无效,则不会渲染任何布局。在这种情况下,指定一个fallback
布局进行渲染。它 必须 与layouts/
目录中相应布局文件的名称匹配。- type:
string
- default:
null
- type:
Additional Props
NuxtLayout
还接受你可能需要传递给布局的任何附加属性。这些自定义属性随后可以作为属性访问。
pages/some-page.vue
<template>
<div>
<NuxtLayout name="custom" title="I am a custom layout">
<-- ... -->
</NuxtLayout>
</div>
</template>
在上面的例子中,title
的值可以在模板中使用 $attrs.title
或在 <script setup>
中使用 useAttrs().title
访问。
layouts/custom.vue
const layoutCustomProps = useAttrs()
console.log(layoutCustomProps.title) // I am a custom layout
Transitions
<NuxtLayout />
通过 <slot />
渲染传入的内容,然后包裹在 Vue 的 <Transition />
组件中以激活布局过渡。为了使其按预期工作,建议 <NuxtLayout />
不 是页面组件的根元素。
<template>
<div>
<NuxtLayout name="custom">
<template #header> Some header template content. </template>
</NuxtLayout>
</div>
</template>
Layout's Ref
要获取布局组件的 ref,通过 ref.value.layoutRef
访问。
<script setup lang="ts">
const layout = ref()
function logFoo () {
layout.value.layoutRef.foo()
}
</script>
<template>
<NuxtLayout ref="layout">
default layout
</NuxtLayout>
</template>