Vue 3.0 - Slots(슬롯)

JungSik Heo·2023년 1월 3일

Vue 3.0 강의

목록 보기
9/29

Props 중심 컴포넌트의 문제점

위와 같이 Props가 거대해 지면 컴포넌트 이해와 확장이 어려워 진다.

slot이란?


슬롯을 이용하면 정해진 공간을 마음대로 채울 수 있다.

슬롯은 표준 html 요소처럼 컨텐츠를 넘길 수 있도록 해주는 도구다.

여러개의 슬롯 사용하기

이를 위해선 named slot과 template block이 필요하다.

📄CustomLayout.vue

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

그럼 특정 슬롯에 컴포넌트는 어떻게 전달할까?

v-slot 디렉티브는 콘텐츠를 표시하길 원하는 슬롯 name 인수를 사용할 수 있다.
v-slot 디렉티브는 탬플릿 요소에서만 사용할 수 있다.

동적 바인딩도 가능

📄App.vue

<template>
  <CustomLayout>
    <template v-slot:header>
      <p>Header content</p>
    </template>
    <template>
      <p>Main body content</p>
    </template>
    <template v-slot:footer>
      <p>Footer content</p>
    </template>
  </CustomLayout>
</template>

정리

  • 슬롯은 컴포넌트에 다양한 유형의 컨텐츠를 제공할 수 있는 유연성을 허용하는 기술이다

https://itchallenger.tistory.com/832

profile
쿵스보이(얼짱뮤지션)

0개의 댓글