[Vue] - 슬롯(slot)

Soozoo·2024년 10월 1일

Vue

목록 보기
17/23

Vue의 slot은 부모 컴포넌트가 자식 컴포넌트 내부의 특정 위치에 콘텐츠를 전달할 수 있게 해주는 기능입니다. 이를 통해 부모 컴포넌트에서 자식 컴포넌트의 레이아웃은 그대로 유지하면서, 그 안의 내용을 동적으로 변경할 수 있습니다.

기본 슬롯 (Default Slot)

기본적으로 부모 컴포넌트에서 자식 컴포넌트에 전달한 콘텐츠는 slot 태그가 있는 곳에 렌더링됩니다. slot을 사용할 때는 별도의 이름을 지정하지 않아도 됩니다.

기본 슬롯 사용 예시:

자식 컴포넌트 (ChildComponent.vue)

<template>
  <div class="child">
    <h2>자식 컴포넌트</h2>
    <slot></slot> <!-- 부모로부터 전달된 콘텐츠가 여기에 렌더링됩니다 -->
  </div>
</template>

부모 컴포넌트 (ParentComponent.vue)

<template>
  <div>
    <h1>부모 컴포넌트</h1>
    <child-component>
      <p>이 콘텐츠는 부모에서 전달되었습니다!</p>
    </child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
};
</script>

결과:

<child-component> 내부에 부모로부터 전달된 <p> 태그의 콘텐츠가 자식 컴포넌트의 slot에 렌더링됩니다.


이름이 있는 슬롯 (Named Slots)

Vue는 여러 개의 slot을 가질 수 있고, 각 슬롯에 이름을 지정할 수 있습니다. 부모는 v-slot 디렉티브를 사용해 콘텐츠를 특정 이름의 슬롯에 전달할 수 있습니다.

이름이 있는 슬롯 사용 예시:

자식 컴포넌트 (ChildComponent.vue)

<template>
  <div class="child">
    <h2>자식 컴포넌트</h2>
    <slot name="header"></slot>  <!-- 'header'라는 이름을 가진 슬롯 -->
    <slot></slot>                <!-- 기본 슬롯 -->
    <slot name="footer"></slot>  <!-- 'footer'라는 이름을 가진 슬롯 -->
  </div>
</template>

부모 컴포넌트 (ParentComponent.vue)

<template>
  <div>
    <h1>부모 컴포넌트</h1>
    <child-component>
      <template v-slot:header>
        <h3>이것은 헤더입니다</h3>
      </template>

      <p>이것은 기본 슬롯에 들어갈 콘텐츠입니다.</p>

      <template v-slot:footer>
        <p>이것은 푸터입니다</p>
      </template>
    </child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
};
</script>

결과:

  • header 슬롯에는 부모가 전달한 <h3> 요소가 렌더링됩니다.
  • 기본 슬롯에는 <p>이것은 기본 슬롯에 들어갈 콘텐츠입니다.</p>가 렌더링됩니다.
  • footer 슬롯에는 <p>이것은 푸터입니다</p>가 렌더링됩니다.

슬롯 속성 (Scoped Slots)

Scoped slots은 자식 컴포넌트가 부모 컴포넌트로 데이터를 전달할 때 유용합니다. 부모는 자식이 전달한 데이터를 v-slot 디렉티브를 통해 접근할 수 있습니다.

Scoped Slot 사용 예시:

자식 컴포넌트 (ChildComponent.vue)

<template>
  <div>
    <slot :user="user"></slot> <!-- 'user' 데이터를 부모로 전달 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {
        name: 'John Doe',
        age: 25
      }
    };
  }
};
</script>

부모 컴포넌트 (ParentComponent.vue)

<template>
  <child-component>
    <template v-slot:default="slotProps">
      <p>사용자 이름: {{ slotProps.user.name }}</p>
      <p>사용자 나이: {{ slotProps.user.age }}</p>
    </template>
  </child-component>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
};
</script>

결과:

  • 자식 컴포넌트에서 전달한 user 데이터를 부모 컴포넌트에서 접근할 수 있으며, 이를 통해 사용자의 이름과 나이를 출력할 수 있습니다.

결론:

  • 기본 슬롯: 부모가 전달한 콘텐츠가 자식 컴포넌트에 있는 slot 태그에 삽입됩니다.
  • 이름이 있는 슬롯: 여러 개의 슬롯을 구분하여 사용할 수 있습니다.
  • Scoped Slots: 자식 컴포넌트에서 데이터를 부모에게 전달할 수 있습니다.

slot은 자식 컴포넌트의 레이아웃을 유지하면서 부모에서 콘텐츠를 동적으로 전달할 수 있는 강력한 기능을 제공합니다.

profile
넙-죽

0개의 댓글