<NuxtLayout>
Nuxt 提供了 <NuxtLayout> 元件,用於在頁面和錯誤頁面上顯示佈局。
您可以使用 <NuxtLayout />
元件在 app.vue
或 error.vue
中啟用 default
佈局。
app/app.vue
<template>
<NuxtLayout>
some page content
</NuxtLayout>
</template>
屬性
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>
<template>
<div>
<!-- named slot -->
<slot name="header" />
<slot />
</div>
</template>
佈局的 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>
<script setup lang="ts">
const foo = () => console.log('foo')
defineExpose({
foo,
})
</script>
<template>
<div>
default layout
<slot />
</div>
</template>