<NuxtLayout>
Nuxt는 페이지와 에러 페이지에서 레이아웃을 표시하기 위해 <NuxtLayout> 컴포넌트를 제공합니다.
<NuxtLayout /> 컴포넌트를 사용하여 app.vue 또는 error.vue에서 default 레이아웃을 활성화할 수 있습니다.
app.vue
<template>
<NuxtLayout>
some page content
</NuxtLayout>
</template>
Props
name: 렌더링할 레이아웃 이름을 지정합니다. 문자열, 반응형 참조 또는 계산된 속성이 될 수 있습니다. 반드시layouts/디렉토리의 해당 레이아웃 파일 이름과 일치해야 합니다.- type:
string - default:
default
- type:
pages/index.vue
<script setup lang="ts">
// layouts/custom.vue
const layout = 'custom'
</script>
<template>
<NuxtLayout :name="layout">
<NuxtPage />
</NuxtLayout>
</template>
레이아웃 이름은 케밥-케이스로 정규화되므로, 레이아웃 파일 이름이
errorLayout.vue인 경우 <NuxtLayout />의 name 속성에 전달할 때는 error-layout이 됩니다.error.vue
<template>
<NuxtLayout name="error-layout">
<NuxtPage />
</NuxtLayout>
</template>
fallback:nameprop에 잘못된 레이아웃이 전달되면 레이아웃이 렌더링되지 않습니다. 이 경우 렌더링할fallback레이아웃을 지정할 수 있습니다. 반드시layouts/디렉토리의 해당 레이아웃 파일 이름과 일치해야 합니다.- type:
string - default:
null
- type:
Additional Props
NuxtLayout은 레이아웃에 전달해야 할 추가 props도 허용합니다. 이러한 커스텀 props는 속성으로 접근할 수 있습니다.
pages/some-page.vue
<template>
<div>
<NuxtLayout name="custom" title="I am a custom layout">
<-- ... -->
</NuxtLayout>
</div>
</template>
위 예시에서 title의 값은 템플릿에서 $attrs.title로, 또는 <script setup>의 custom.vue에서 useAttrs().title로 사용할 수 있습니다.
layouts/custom.vue
<script setup lang="ts">
const layoutCustomProps = useAttrs()
console.log(layoutCustomProps.title) // 나는 커스텀 레이아웃입니다
</script>
Transitions
<NuxtLayout />는 들어오는 콘텐츠를 <slot />을 통해 렌더링하며, 이는 Vue의 <Transition /> 컴포넌트로 감싸져 레이아웃 전환을 활성화합니다. 기대한 대로 동작하려면 <NuxtLayout />이 페이지 컴포넌트의 루트 요소가 아니어야 합니다.
<template>
<div>
<NuxtLayout name="custom">
<template #header> Some header template content. </template>
</NuxtLayout>
</div>
</template>
<template>
<div>
<!-- 명명된 슬롯 -->
<slot name="header" />
<slot />
</div>
</template>
Layout's 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>