Vue slot이란?

청포도봉봉이·2023년 4월 28일
0

Vue

목록 보기
8/11
post-thumbnail

Slot의 개념

Slot은 컴포넌트의 템플릿에서 다른 컴포넌트나 HTML 요소를 삽입하는 기능을 의미합니다. Slot을 사용하면 다른 컴포넌트나 HTML 코드의 일부를 동적으로 삽입하면서 컴포넌트를 재사용할 수 있습니다.

UserProfile.vue (자식)

<template>
    <div class="user-container">
    <div>
      <i class="fa-solid fa-user"></i>
    </div>
    <div class="user-description">
      <slot name="username"></slot>
      <div class="time">
        <slot name="time"></slot>
      </div>
      <slot name="karma"></slot>
    </div>
  </div>
</template>

자식에서는 <slot name="슬롯이름"></slot>을 통해서 같은 이름의 슬롯 설정 후 html을 내려받을 수 있다.


ItemView.vue (부모)

<template>
  <div>
    <section>
      <UserProfile :info="getInfoItem">
        <template v-slot:username>
          <div>{{ getInfoItem.user }}</div>
        </template>
        <template v-slot:time>
          {{ getInfoItem.time_ago }}
        </template>
      </UserProfile>
    </section>
    <section>
      <h2>{{ getInfoItem.title }}</h2>
    </section>
    <section>
      <div v-html="getInfoItem.content"></div>
    </section>
  </div>
</template>

UserView.vue (부모)

<template>
  <UserProfile :info="userInfo">
    <template v-slot:username>
      <div>{{ userInfo.id }}</div>
    </template>
    <template v-slot:time>
      {{ userInfo.created }}
    </template>
    <template v-slot:karma>
      {{ userInfo.karma }}
    </template>
  </UserProfile>
</template>

부모에서는 <template v-slot:슬롯이름><h1>Hello World</h1></template> 을 통해서 template 마크업안에 있는 h1태그부터 내려줄 수 있다.

profile
자존감 낮아질 시간에 열심히 공부하고 커밋하자😊😊

0개의 댓글