<NuxtLayout>

Nuxt 提供了 <NuxtLayout> 组件,用于在页面和错误页面上显示布局。

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

¥You can use <NuxtLayout /> component to activate the default layout on app.vue or error.vue.

app.vue
<template>
  <NuxtLayout>
    some page content
  </NuxtLayout>
</template>
Read more in Docs > Guide > Directory Structure > Layouts.

Props

  • name:指定要渲染的布局名称,可以是字符串、响应式引用或计算属性。它必须与 layouts/ 目录中相应布局文件的名称匹配。
    • 类型:string
    • 默认:default
pages/index.vue
<script setup lang="ts">
// layouts/custom.vue
const layout = 'custom'
</script>

<template>
  <NuxtLayout :name="layout">
    <NuxtPage />
  </NuxtLayout>
</template>
请注意,布局名称已规范化为短横线命名,因此如果你的布局文件名为 errorLayout.vue,则在将其作为 name 属性传递给 <NuxtLayout /> 时,它将变为 error-layout
error.vue
<template>
  <NuxtLayout name="error-layout">
    <NuxtPage />
  </NuxtLayout>
</template>

:

Read more in Docs > Guide > Directory Structure > Layouts.

阅读更多关于动态布局的内容。

¥Read more about dynamic layouts.

::

  • fallback:如果将无效的布局传递给 name 属性,则不会渲染任何布局。指定在此场景中要渲染的 fallback 布局。它必须与 layouts/ 目录中相应布局文件的名称匹配。
    • 类型:string
    • 默认:null

其他 Props

¥Additional Props

NuxtLayout 还接受你可能需要传递给布局的任何其他 props。这些自定义 props 可以作为属性访问。

¥NuxtLayout also accepts any additional props that you may need to pass to the layout. These custom props are then made accessible as attributes.

pages/some-page.vue
<template>
  <div>
    <NuxtLayout name="custom" title="I am a custom layout">
      <-- ... -->
    </NuxtLayout>
  </div>
</template>

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

¥In the above example, the value of title will be available using $attrs.title in the template or useAttrs().title in <script setup> at custom.vue.

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

console.log(layoutCustomProps.title) // I am a custom layout
</script>

过渡

¥Transitions

<NuxtLayout /> 通过 <slot /> 渲染传入的内容,然后将其封装在 Vue 的 <Transition /> 组件中以激活布局转换。为此,Nuxt 提供了 <NuxtLayout /> 实用程序,它既会将模板写入磁盘,又会在生成的 文件中添加对模板的引用。

¥<NuxtLayout /> renders incoming content via <slot />, which is then wrapped around Vue’s <Transition /> component to activate layout transition. For this to work as expected, it is recommended that <NuxtLayout /> is not the root element of the page component.

<template>
  <div>
    <NuxtLayout name="custom">
      <template #header> Some header template content. </template>
    </NuxtLayout>
  </div>
</template>
Read more in Docs > Getting Started > Transitions.

布局的引用

¥Layout's Ref

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

¥To get the ref of a layout component, access it through 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>
Read more in Docs > Guide > Directory Structure > Layouts.