NuxtLayOut
Nuxt 提供了 <NuxtLayout>
组件来在页面和错误页面上显示布局。
你可以使用 <NuxtLayout />
组件在 app.vue
或 error.vue
上激活 default
布局。
html
<template>
<NuxtLayout> 页面内容 </NuxtLayout>
</template>
Props
name
: 指定要渲染的布局名称,可以是字符串、响应式引用或计算属性。它必须与 layouts/
目录中相应布局文件的名称匹配。
类型: string
默认值:default
html
<script setup lang="ts">
// layouts/custom.vue
const layout = "custom";
</script>
<template>
<NuxtLayout :name="layout">
<NuxtPage />
</NuxtLayout>
</template>
bash
请注意,布局名称会被转换为 `kebab-case`
因此,如果你的布局文件名为 `errorLayout.vue`
当作为 `name` 属性传递给 `<NuxtLayout />` 时,它将变为 `error-layout`。
html
<template>
<NuxtLayout name="error-layout">
<NuxtPage />
</NuxtLayout>
</template>
附加 Props
NuxtLayout
还接受任何你可能需要传递给布局的附加 props
。这些自定义 props 会作为属性可访问
html
<template>
<div>
<NuxtLayout name="custom" title="我是一个自定义布局">
<-- ... -->
</NuxtLayout>
</div>
</template>
在上面的示例中,title
的值可以在模板中使用 $attrs.title
或在 <script setup>
中使用 useAttrs().title
来访问
html
<!-- layouts/custom.vue -->
<script setup lang="ts">
const layoutCustomProps = useAttrs();
console.log(layoutCustomProps.title); // 我是一个自定义布局
</script>
过渡效果
<NuxtLayout />
通过 <slot />
渲染传入的内容,然后将其包装在 Vue 的 <Transition />
组件中以激活布局过渡效果。为了使其按预期工作,建议 <NuxtLayout />
不是页面组件的根元素。
html
<template>
<div>
<NuxtLayout name="custom">
<template #header> 页面头部模板内容。 </template>
</NuxtLayout>
</div>
</template>
布局的 Ref
要获取布局组件的 ref,请通过 ref.value.layoutRef 访问。
- app.vue
html
<script setup lang="ts">
const layout = ref();
function logFoo() {
layout.value.layoutRef.foo();
}
</script>
<template>
<NuxtLayout ref="layout" />
</template>