<NuxtLayout>

源码
Nuxt 提供 <NuxtLayout> 组件以在页面和错误页面上显示布局。

您可以使用 <NuxtLayout /> 组件在 app.vueerror.vue 上激活 default 布局。

app/app.vue
<template>
  <NuxtLayout>
    一些页面内容
  </NuxtLayout>
</template>
Docs > Directory Structure > App > Layouts 中阅读更多。

Props

  • 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>

Missing link 中阅读更多。
{to="/docs/directory-structure/app/layouts} 阅读更多关于动态布局的信息。 ::

  • fallback: 如果将无效的布局传递给 name prop,则不会渲染任何布局。指定在这种情况下要渲染的 fallback 布局。它必须app/layouts/ 目录中相应布局文件的名称匹配。
    • 类型: string
    • 默认值: null

额外的 Props

NuxtLayout 还接受您可能需要传递给布局的任何其他 props。这些自定义 props 然后作为属性可用。

app/pages/some-page.vue
<template>
  <div>
    <NuxtLayout
      name="custom"
      title="我是一个自定义布局"
    >
      <!-- ... -->
    </NuxtLayout>
  </div>
</template>

在上面的示例中,title 的值将可以在 custom.vue 的模板中使用 $attrs.title 或在 <script setup> 中使用 useAttrs().title 访问。

app/layouts/custom.vue
<script setup lang="ts">
const layoutCustomProps = useAttrs()

console.log(layoutCustomProps.title) // 我是一个自定义布局
</script>

过渡

<NuxtLayout /> 通过 <slot /> 渲染传入的内容,然后将其包装在 Vue 的 <Transition /> 组件周围以激活布局过渡。为了使其按预期工作,建议 <NuxtLayout /> 不是页面组件的根元素。

<template>
  <div>
    <NuxtLayout name="custom">
      <template #header>
        一些页眉模板内容。
      </template>
    </NuxtLayout>
  </div>
</template>
https://nuxt.com/docs/guide/routing 中阅读更多。

布局的 Ref

要获取布局组件的 ref,通过 ref.value.layoutRef 访问它。

<script setup lang="ts">
const layout = ref()

function logFoo () {
  layout.value.layoutRef.foo()
}
</script>

<template>
  <NuxtLayout ref="layout">
    默认布局
  </NuxtLayout>
</template>
Docs > Directory Structure > App > Layouts 中阅读更多。