components
디렉토리는 페이지 또는 다른 컴포넌트 내에서 가져올 수 있는 모든 Vue 컴포넌트를 저장한다.components
디렉토리에 있는 모든 컴포넌트를 자동으로 가져와서 별도로 import를 하여 가져오지 않아도 된다.| components/
--| Header.vue
--| Footer.vue
<template>
<div>
<Header />
<slot />
<Footer />
</div>
</template>
components
디렉토리만 스캔한다. 만약 다른 디렉토리를 추가하거나 components
디렉토리의 하위 폴더 내에 파일을 컴포넌트로 인식하려면 nuxt.config.ts
에 디렉토리를 추가하면 된다.extensions
: extenstions
에 지정된 확장자를 가진 모든 파일은 컴포넌트로 취급export default defineNuxtConfig({
components: [
{
path: '~/components/special-components',
prefix: 'Special',
extensions: ['.vue'],
},
]
})
base/foo
폴더에 Button.vue
가 있으므로 컴포넌트명은 <BaseFooButton />
이 된다.| components/
--| base/
----| foo/
------| Button.vue
<BaseFooButton />
pathPrefix
를 false
로 지정한다.export default defineNuxtConfig({
components: [
{
path: '~/components',
+ pathPrefix: false,
},
],
});
<component :is="일부 계산된 컴포넌트">
구문을 사용하려면 Vue에서 제공하는 resolveComponent()
를 사용한다.resolveComponent()
: 변수가 아닌 문자열이어야 하며 컴포넌트명만 기입<template>
<component :is="clickable ? MyButton : 'div'" />
</template>
<script setup>
const MyButton = resolveComponent('MyButton')
</script>
nuxt.config.ts
에 등록하거나 components/global
디렉토리에 배치하여 등록export default defineNuxtConfig({
components: {
+ global: true,
+ dirs: ['~/components']
},
})
Lazy
란 접두사만 추가하면 된다.<template>
<div>
<TheHeader />
<slot />
<LazyTheFooter />
</div>
</template>
#components
를 통해 컴포넌트를 명시적으로 가져올 수 있다.<template>
<div>
<h1>Mountains</h1>
<LazyMountainsList v-if="show" />
<button v-if="!show" @click="show = true">Show List</button>
<NuxtLink to="/">Home</NuxtLink>
</div>
</template>
<script setup>
import { NuxtLink, LazyMountainsList } from '#components'
const show = ref(false)
</script>
<ClientOnly>
컴포넌트<ClientOnly>
컴포넌트를 제공한다.<template>
<div>
<Sidebar />
<ClientOnly>
<!-- this component will only be rendered on client-side -->
<Comments />
</ClientOnly>
</div>
</template>
.client
접미사를 추가하여 사용할 수 있다.| components/
--| Comments.client.vue
<template>
<div>
<!-- this component will only be rendered on client side -->
<Comments />
</div>
</template>
💡 .client
컴포넌트는 마운트된 후에만 렌더링된다. 렌더링된 템플릿에 사용하려면 onMounted()
훅에 await nextTick()
을 추가하면 된다.