[Vue] 컴포넌트 - slot

youngseo·2022년 5월 2일
0
post-thumbnail

한 번에 끝내는 프론트엔드 개발 초격차 패키지 Online를 들으며 정리한 내용입니다.

slot

1. Fallback Contents(대체컨텐츠)

App.vue

<template>
  <MyBtn>
    Banana   //만약 텍스트가 입력되지 않는다면?
  </MyBtn>
</template>

MyBtn.vue

<template>
  <div class="btn">
    <slot></slot>
  </div>
</template>

부모 컴포넌트의 MyBtn태그 사이에 Banana텍스트를 작성하지 않게 되면 화면에 텍스트가 없는 상태로 출력이 되게 됩니다.

이를 자식컴포넌트의 slot사이에 텍스트를 작성해 보완해줄 수 있습니다.

MyBtn.vue

<template>
  <div class="btn">
    <slot>Apple</slot>
  </div>
</template>

이렇게 slot 태그 내에 텍스트를 입력하면, 그 내용인 Apple이 출력됩니다. 이는 부모 컴포넌트에 내용이 없을 경우에만 출력되며 부모 컴포넌트에 텍스트가 있다면 해당 내용이 우선 출력됩니다.

이렇게 slot 태그 내에 입력한 컨텐츠를 Fallback Contents라 부릅니다. 이는 대체 컨텐츠라는 의미입니다.

2. Named Slots(이름을 갖는 슬롯)

<template>
  <MyBtn>
    <span>(B)</span>
    <span>Banana</span>
  </MyBtn>
</template>

이렇게 MyBtn태그 내의 모든 내용이 slot태그를 대신해서 들어갈 수 있습니다. 단, 위 코드에서 순서가 바뀌게 된다면 아래와 같이 Banana다음에 (B)가 축겨되게 됩니다.

<template>
  <MyBtn>
    <span>Banana</span>   ✔️순서가 바뀐다면?
    <span>(B)</span>
  </MyBtn>
</template>

만약, 이러한 내용들이 정확하게 순서를 갖춰서 내용이 동작하게 하고 싶다면 이름을 갖는 슬롯(Named Slots)을 이용할 수 있습니다.

실습

(B)는 하나의 icon을 Banana는 text를 의미한다고 가정하고 실습을 해보도록 하겠습니다. icon이 나오고 그다음에 text가 나오는 구조를 보장해주는 코드를 작성해보도록 하겠습니다.

MyBtn.vue

<template>
  <div class="btn">
    <slot name="icon"></slot>
    <slot name="text"></slot>
  </div>
</template>

App.vue

<template>
  <MyBtn>
    <template #icon>  //v-slot:icon 이 #icon과 같은 약어로 작성할 수 있습니다.
      <span>(B)</span>
    </template>   
    <template #text>
      <span>Banana</span> 
    </template>  
  </MyBtn>
</template>

위의 순서를 바꾸어작성을 하더라도
App.vue

<template>
  <MyBtn>
    <template #text>
      <span>Banana</span> 
    </template>  
    <template #icon>  //v-slot:icon 이 #icon과 같은 약어로 작성할 수 있습니다.
      <span>(B)</span>
    </template>   
  </MyBtn>
</template>

보장된 순서 그대로 출력이 되게 됩니다.

0개의 댓글