Vue/Vue.js 문법
Vue.js 문법 - 컴포넌트 Slot
IT Blue
2021. 7. 18. 18:53
대체 콘텐츠 (Fallback Contents)
App.vue
<template>
<MyBtn>
Banana
</MyBtn>
</template>
MyBtn.vue
<template>
<div class="btn">
<slot>Apple</slot>
</div>
</template>
결과
코드 이해하기
- slot 태그를 사용하면 부모 컴포넌트 사이에 있는 컨텐츠 (Banana)를 받아준다
- 부모 컴포넌트에 컨텐츠가 없는 경우에는 대체 컨텐츠 (Apple)가 표시된다
- 부모 컴포넌트에 컨텐츠가 있는 경우에는 대체 컨텐츠는 표시되지 않는다
- 이러한 개념을 대체 컨텐츠 Fallback Contents 라고 부른다
이름을 갖는 슬롯 (Named Slots)
App.vue
<template>
<MyBtn>
<template #text>
<span>Banana</span>
</template>
<template #icon>
<span>(B)</span>
</template>
</MyBtn>
</template>
MyBtn.vue
<template>
<div class="btn">
<slot name="icon"></slot>
<slot name="text"></slot>
</div>
</template>
결과
코드 이해하기
- slot 태그에 name을 부여하여 부모 컴포넌트에서 이름을 가진 컨텐츠가 해당 slot으로 들어감
- 부모 컴포넌트에서는 v-slot: 디렉티브를 사용해서 이름을 부여, 약어는 #
- 순서를 보장해줄 수 있다