<NuxtLayout>

原始檔
Nuxt 提供了 <NuxtLayout> 元件,用於在頁面和錯誤頁面上顯示佈局。

您可以使用 <NuxtLayout /> 元件在 app.vueerror.vue 中啟用 default 佈局。

app/app.vue
<template>
  <NuxtLayout>
    some page content
  </NuxtLayout>
</template>
文件 > 4 X > 指南 > 目錄結構 > App > 佈局中閱讀更多內容。

屬性

  • name:指定要渲染的佈局名稱,可以是字串、響應式引用或計算屬性。它必須app/layouts/ 目錄中相應佈局檔案的名稱匹配。
    • 型別string
    • 預設值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>
閱讀更多關於動態佈局的資訊。
  • fallback:如果傳遞給 name 屬性的佈局無效,則不會渲染任何佈局。在此情況下,指定一個 fallback 佈局進行渲染。它必須app/layouts/ 目錄中相應佈局檔案的名稱匹配。
    • 型別string
    • 預設值null

額外屬性

NuxtLayout 也接受您可能需要傳遞給佈局的任何額外屬性。這些自定義屬性隨後作為屬性訪問。

app/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 訪問。

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

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

過渡

<NuxtLayout /> 透過 <slot /> 渲染傳入的內容,然後將其包裝在 Vue 的 <Transition /> 元件中以啟用佈局過渡。為了使其按預期工作,建議 <NuxtLayout /> 不是頁面元件的根元素。

<template>
  <div>
    <NuxtLayout name="custom">
      <template #header>
        Some header template content.
      </template>
    </NuxtLayout>
  </div>
</template>
文件 > 4 X > 入門 > 過渡中閱讀更多內容。

佈局的 Ref

要獲取佈局元件的 ref,可以透過 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>
文件 > 4 X > 指南 > 目錄結構 > App > 佈局中閱讀更多內容。