通过将 <NuxtLayout> 添加到你的 app.vue 来启用布局。
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
使用布局
layout 属性。<NuxtLayout> 的 name 属性。someLayout 会变成 some-layout。app/layouts/default.vue。app.vue。<slot />。添加 ~/layouts/default.vue
<template>
<div>
<p>Some default layout content shared across all pages</p>
<slot />
</div>
</template>
在布局文件中,页面的内容将显示在 <slot /> 组件中。
-| layouts/
---| default.vue
---| custom.vue
然后你可以在你的页面中使用 custom 布局
<script setup lang="ts">
definePageMeta({
layout: 'custom',
})
</script>
你可以使用 <NuxtLayout> 的 name 属性直接覆盖所有页面的默认布局。
<script setup lang="ts">
// You might choose this based on an API call or logged-in status
const layout = 'custom'
</script>
<template>
<NuxtLayout :name="layout">
<NuxtPage />
</NuxtLayout>
</template>
如果你的布局位于嵌套目录中,布局的名称将基于其自身的路径目录和文件名,并移除重复的片段。
| 文件 | 布局名称 |
|---|---|
~/layouts/desktop/default.vue | desktop-default |
~/layouts/desktop-base/base.vue | desktop-base |
~/layouts/desktop/index.vue | desktop |
为清晰起见,我们建议布局的文件名与其名称匹配
| 文件 | 布局名称 |
|---|---|
~/layouts/desktop/DesktopDefault.vue | desktop-default |
~/layouts/desktop-base/DesktopBase.vue | desktop-base |
~/layouts/desktop/Desktop.vue | desktop |
你还可以使用 setPageLayout 辅助函数动态更改布局。
<script setup lang="ts">
function enableCustomLayout () {
setPageLayout('custom')
}
definePageMeta({
layout: false,
})
</script>
<template>
<div>
<button @click="enableCustomLayout">
Update layout
</button>
</div>
</template>
如果你正在使用页面,你可以通过设置 layout: false 然后在页面内使用 <NuxtLayout> 组件来完全控制。
<script setup lang="ts">
definePageMeta({
layout: false,
})
</script>
<template>
<div>
<NuxtLayout name="custom">
<template #header>
Some header template content.
</template>
The rest of the page
</NuxtLayout>
</div>
</template>
<template>
<div>
<header>
<slot name="header">
Default header content
</slot>
</header>
<main>
<slot />
</main>
</div>
</template>
<NuxtLayout>,请确保它不是根元素(或禁用布局/页面过渡)。