Vue.js 컴포넌트 간의 컨텐츠를 전달하는 <slot> 태그 ( + Named Slot)

Slot

<slot> 태그는 컴포넌트 간의 컨텐츠 전달을 위해 사용되는 방식 중 하나입니다.

<slot> 태그를 이용하면 부모 컴포넌트에서 자식 컴포넌트로 컨텐츠를 삽입하여 동적으로 컴포넌트를 구성할 수 있습니다.

<slot> 태그를 사용하여 컨텐츠 뿐만 아니라 컴포넌트를 넘길 수도 있습니다. 자세한 설명을 하기보다는 일단 아래 예제로 설명하도록 하겠습니다.

 

 

컨텐츠 전달

Parent Component

<template>
  <div>
    <h2>Parent Component</h2>
    <child-component>
      <p>자식 컴포넌트로 전달할 컨텐츠</p>
    </child-component>
  </div>
</template>

 

Child Component

<template>
  <div>
    <h2>Child Component</h3>
    <slot></slot>
  </div>
</template>

 

컴포넌트가 렌더링될 때 부모 컴포넌트의 <child-component> 안에 있는 컨텐츠들이 <slot> 태그 위치에 렌더링 됩니다.

이런 식으로 <slot> 태그를 사용하면 부모 컴포넌트에서 자식 컴포넌트로 컨텐츠를 전달하여 컴포넌트의 일부를 동적으로 변환할 수 있습니다.

 

 

컴포넌트 전달

또한 <slot> 태그에 다른 컴포넌트를 삽입하는 것도 가능합니다.

아래 예시는 <demo-content> 컴포넌트를 <child-component> 컴포넌트 slot에 전달하는 코드입니다.

당연히 만약 <child-component> 컴포넌트가 <slot> 태그를 갖고 있지 않다면 적용되지 않습니다.

<template>
  <div>
    <h2>Parent Component</h2>
    <child-component>
      <demo-content />
    </child-component>
  </div>
</template>

 

 

<slot> 기본값 설정

`<slot>` 태그에 기본 컨텐츠를 지정할 수도 있습니다.

만약 부모 컴포넌트에서 컨텐츠를 전달하지 않았을 경우 보이는 기본값입니다.

<template>
  <div>
    <h2>Child Component</h3>
    <slot>Default Content</slot>
  </div>
</template>

위와 같이 자식 컴포넌트(전달 받는 컴포넌트)에서 <slot>태그 사이에 컨텐츠를 집어넣어 '기본 컨텐츠'를 설정할 수 있습니다. 부모 컴포넌트에서 컨텐츠를 전달하지 않았을 경우, 기본 컨텐츠가 렌더링 됩니다.

 


Named Slot

<slot> 태그에 이름을 지정하여 여러 slot을 사용할 수 있습니다.

이름을 지정함으로써 부모 컴포넌트에서 자식 컴포넌트로 여러 개의 slot을 전달하고, 자식 컴포넌트에서는 각각의 slot에 해당하는 컨텐츠를 동적으로 렌더링 할 수 있습니다.

 

Parent Component

<template>
  <div>
    <child-component>
      <template #header>
        <h2>Header 컨텐츠</h2>
      </template>
      <template #body>
        <p>Content 컨텐츠</p>
      </template>
      <template #footer>
        <p>Content 컨텐츠</p>
      </template>
    </child-component>
  </div>
</template>

 

child Component

<template>
  <div>
    <slot name="header"></slot>
    <slot name="body"></slot>
    <slot name="footer"></slot>
  </div>
</template>

 

name이 지정된 slot에 내용을 전달하기 위해서는 <template> 태그에 `v-slot 디렉티브`를 사용하여야 합니다. 하지만 위 예시와 같이 단축 표기로 `#`을 사용하는 것이 가능합니다.

만약 name이 지정되지 않은 <slot> 태그인 경우 default 값이 사용됩니다.

 

 

`<slot>` 태그를 사용하면 컴포넌트 간의 컨텐츠 전달이 쉽고 간편해지고 재사용성이 높아집니다.