<NuxtLayout>
Nuxt 提供了 <NuxtLayout> 组件,用于在页面和错误页面中显示布局。
Maschinelle Übersetzung ·0 % geprüft
你可以使用 <NuxtLayout /> 组件在 app.vue 或 error.vue 中激活 default 布局。
app/app.vue
<template>
<NuxtLayout>
some page content
</NuxtLayout>
</template>属性
name:指定要渲染的布局名称,可以是字符串、响应式引用或计算属性。它必须与app/layouts/目录中对应布局文件的名称匹配,或者设为false以禁用布局。- 类型:
string | false - 默认值:
default
- 类型:
app/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布局,以便在这种情况下渲染。它必须与app/layouts/目录中对应布局文件的名称匹配。- 类型:
string - 默认值:
null
- 类型:
额外属性
NuxtLayout 还接受你可能需要传递给布局的任何额外属性。这些自定义属性随后会作为属性(attributes)可用。
app/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 访问。
app/layouts/custom.vue
<script setup lang="ts">
const layoutCustomProps = useAttrs()
console.log(layoutCustomProps.title) // Ich bin ein benutzerdefiniertes Layout
</script>从页面元信息(Page Meta)获取的布局属性
使用 definePageMeta 并以对象语法设置 layout 时,属性会自动传递给布局组件。布局可以通过 defineProps 接收这些属性:
app/pages/dashboard.vue
<script setup lang="ts">
definePageMeta({
layout: {
name: 'admin',
props: {
sidebar: true,
},
},
})
</script>app/layouts/admin.vue
<script setup lang="ts">
const props = defineProps<{
sidebar?: boolean
}>()
</script>过渡
<NuxtLayout /> 通过 <slot /> 渲染传入内容,随后该内容会被包裹在 Vue 的 <Transition /> 组件中以启用布局过渡。为使其按预期工作,建议 <NuxtLayout /> 不要 作为页面组件的根元素。
<template>
<div>
<NuxtLayout name="custom">
<template #header>
Some header template content.
</template>
</NuxtLayout>
</div>
</template><template>
<div>
<!-- benannter Slot -->
<slot name="header" />
<slot />
</div>
</template>布局的 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><script setup lang="ts">
const foo = () => console.log('foo')
defineExpose({
foo,
})
</script>
<template>
<div>
default layout
<slot />
</div>
</template>