layouts
启用布局
¥Enable Layouts
通过将 <NuxtLayout>
添加到你的 app.vue
来启用布局:
¥Layouts are enabled by adding <NuxtLayout>
to your app.vue
:
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
要使用布局:
¥To use a layout:
- 在页面中使用 definePageMeta 设置
layout
属性。 - 设置
<NuxtLayout>
的name
属性。
someLayout
变为 some-layout
。layouts/default.vue
。app.vue
。<slot />
。默认布局
¥Default Layout
添加 ~/layouts/default.vue
:
¥Add a ~/layouts/default.vue
:
<template>
<div>
<p>Some default layout content shared across all pages</p>
<slot />
</div>
</template>
在布局文件中,页面内容将显示在 <slot />
组件中。
¥In a layout file, the content of the page will be displayed in the <slot />
component.
命名布局
¥Named Layout
-| layouts/
---| default.vue
---| custom.vue
然后,你可以在页面中使用 custom
布局:
¥Then you can use the custom
layout in your page:
<script setup lang="ts">
definePageMeta({
layout: 'custom'
})
</script>
:
了解更多关于 definePageMeta
的信息。
¥Learn more about definePageMeta
.
::
你可以使用 <NuxtLayout>
的 name
属性直接覆盖所有页面的默认布局:
¥You can directly override the default layout for all pages using the name
property of <NuxtLayout>
:
<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>
如果你的布局位于嵌套目录中,则布局的名称将基于其自身的路径目录和文件名,并删除重复的段。
¥If you have a layout in nested directories, the layout's name will be based on its own path directory and filename, with duplicate segments being removed.
文件 | 布局名称 |
---|---|
~/layouts/desktop/default.vue | desktop-default |
~/layouts/desktop-base/base.vue | desktop-base |
~/layouts/desktop/index.vue | desktop |
为了清楚起见,我们建议布局的文件名与其名称匹配:
¥For clarity, we recommend that the layout's filename matches its name:
文件 | 布局名称 |
---|---|
~/layouts/desktop/DesktopDefault.vue | desktop-default |
~/layouts/desktop-base/DesktopBase.vue | desktop-base |
~/layouts/desktop/Desktop.vue | desktop |
更改动态布局
¥Changing the Layout Dynamically
你还可以使用 setPageLayout
助手动态更改布局:
¥You can also use the setPageLayout
helper to change the layout dynamically:
<script setup lang="ts">
function enableCustomLayout () {
setPageLayout('custom')
}
definePageMeta({
layout: false,
});
</script>
<template>
<div>
<button @click="enableCustomLayout">Update layout</button>
</div>
</template>
逐页覆盖布局
¥Overriding a Layout on a Per-page Basis
如果你使用页面,你可以通过设置 layout: false
然后在页面中使用 <NuxtLayout>
组件来实现完全控制。
¥If you are using pages, you can take full control by setting layout: false
and then using the <NuxtLayout>
component within the page.
<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>
,请确保它不是根元素(或 disable layout/page transitions)。