본문 바로가기
프로그래밍

Vue3에서 Slots는 어떻게 달라졌을까? – 기본 슬롯부터 named slot, scoped slot까지 정리

by 유형제맘 2025. 7. 29.

1. Slot이란?

<slot>은 부모 컴포넌트가 자식 컴포넌트에 콘텐츠를 주입할 수 있게 해주는 기능입니다. Vue에서 컴포넌트를 유연하게 재사용할 수 있게 해주는 핵심 도구예요.

2. Vue2 vs Vue3의 Slot 개선점

항목 Vue2 Vue3
기본 사용 <slot></slot> 동일
이름 있는 슬롯 (named slot) slot="name" #name 또는 v-slot:name
스코프 슬롯 (scoped slot) slot-scope 사용 v-slot으로 통합
타입 지원 제한적 TypeScript 지원 강화
setup()에서 접근 어려움 useSlots()로 쉽게 접근 가능

3. Slot의 종류와 사용 예시

1) 기본 슬롯 (default slot)

<!-- 부모 -->
<CustomCard>
  <p>이건 기본 슬롯 내용입니다.</p>
</CustomCard>

<!-- 자식 -->
<template>
  <div class="card">
    <slot />
  </div>
</template>

2) 이름 있는 슬롯 (named slot)

<!-- 부모 -->
<CustomLayout>
  <template #header>
    <h1>헤더 콘텐츠</h1>
  </template>
  <template #footer>
    <p>푸터 콘텐츠</p>
  </template>
</CustomLayout>

<!-- 자식 -->
<template>
  <header><slot name="header" /></header>
  <main><slot /></main>
  <footer><slot name="footer" /></footer>
</template>

Vue3에서는 #header처럼 짧은 문법이 도입됨 (v-slot:header와 동일)

3) 스코프 슬롯 (scoped slot)

<!-- 부모 -->
<CustomList :items="fruits">
  <template #default="{ item, index }">
    <li>{{ index }}: {{ item }}</li>
  </template>
</CustomList>

<!-- 자식 -->
<template>
  <ul>
    <slot v-for="(item, index) in items" :item="item" :index="index" />
  </ul>
</template>

<script setup>
defineProps(['items'])
</script>

Vue3에서는 v-slot이 모든 슬롯에 대해 통합 문법으로 쓰이며 #default 또는 #이름 방식으로 간결하게 작성 가능

4. setup()에서 슬롯 접근하기

Vue3에서는 <script setup> 또는 Composition API 안에서 useSlots를 사용해 코드상으로도 슬롯 내용을 확인할 수 있습니다.

<script setup>
import { useSlots } from 'vue'

const slots = useSlots()

if (slots.header) {
  console.log('헤더 슬롯이 있음!')
}
</script>

5. 요약

  • Vue3에서도 기본 슬롯, named 슬롯, scoped 슬롯 개념은 동일하게 유지
  • v-slot으로 문법이 통합되고 # 축약 문법 도입
  • useSlots()로 setup()에서도 슬롯에 접근 가능
  • TypeScript 지원이 개선되어 더 안전한 컴포넌트 설계 가능