Vue slot

정현승·2025년 1월 9일

슬롯

템플릿 조각을 자식 컴포넌트에 전달하고 자식 컴포넌트가 자체 템플릿 내에서 조각을 렌더링하도록 할 수 있습니다.

<FancyButton>
  클릭하기! <!-- 슬롯 컨텐츠 -->
</FancyButton>
<button class="fancy-btn">
  <slot></slot> <!-- 슬롯 아울렛 -->
</button>

슬롯 사용 시, FancyButton이 button을 렌더링하고, 내부 컨텐츠를 자식 컴포넌트에게 제공합니다.
슬롯을 사용하면 재사용한 컴포넌트를 만들 수 있습니다.

렌더링 범위

슬롯 컨텐츠는 부모 컴포넌트에 정의되어 있으므로 부모 컴포넌트의 데이터 범위에 접근할 수 있습니다.
슬롯 콘텐츠에는 하위 컴포넌트의 데이터에 대한 액세스 권한이 없습니다.

대체 컨텐츠

슬롯에 대체(fallback) 컨텐츠를 지정하여, 컨텐츠가 제공되지 않을 때만 렌더링되도록 할 수 있습니다.

<button type="submit">
  <slot>
    제출 <!-- 대체 컨텐츠 -->
  </slot>
</button>

이름이 있는 슬롯

단일 컴포넌트에 여러 개의 슬롯 아울렛이 있는 경우 사용합니다.
name이 없는 slot 아울렛은 암시적으로 "default"라는 이름을 갖습니다.

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

이름이 있는 슬롯을 전달하려면, template 엘리먼트와 함께 v-slot 디렉티브를 사용하고, 슬롯 이름을 v-slot (#)에 인자로 전달해야 합니다

<BaseLayout>
  <template #:header>
    <!-- 헤더 슬롯의 컨텐츠 -->
  </template>
</BaseLayout>

동적인 슬롯 이름

<base-layout>
  <template v-slot:[dynamicSlotName]>
    ...
  </template>

  <!-- 단축 문법 사용 -->
  <template #[dynamicSlotName]>
    ...
  </template>
</base-layout>

범위가 지정된 슬롯

props를 컴포넌트에 전달하는 것처럼 속성을 슬롯 아울렛에 전달할 수 있습니다

<!-- <MyComponent> 템플릿 -->
<div>
  <slot :text="greetingMessage" :count="1"></slot>
</div>
<!-- 부모 템플릿 -->
<MyComponent v-slot="{ text, count }">
  {{ text }} {{ count }}
</MyComponent>

이름이 있고 범위가 지정된 슬롯

<MyComponent>
  <template #header="headerProps">
    {{ headerProps }}
  </template>

  <template #default="defaultProps">
    {{ defaultProps }}
  </template>

  <template #footer="footerProps">
    {{ footerProps }}
  </template>
</MyComponent>

0개의 댓글