VUE.JS

[VUE.JS] 컴포넌트 emit, slot

mikrw 2023. 2. 10. 10:43

https://v3-docs.vuejs-korea.org/guide/components/events.html

 

컴포넌트 이벤트 | Vue.js

 

v3-docs.vuejs-korea.org

 

emit

이벤트 선언

// 부모
<BlogPost
  ...
  @enlarge-text="postFontSize += 0.1"
 />


// 자식
<!-- BlogPost.vue의 <script> 생략 -->
<template>
  <div class="blog-post">
    <h4>{{ title }}</h4>
    <button @click="$emit('enlarge-text')">텍스트 확대</button>
  </div>
</template>


<!-- BlogPost.vue -->
<script>
export default {
  props: ['title'],
  emits: ['enlarge-text']
}
</script>

slot

부모가 제공한 슬롯 컨텐츠가 렌더링되어야 하는 위치를 나타내는 슬롯 아울렛(outlet)

https://v3-docs.vuejs-korea.org/guide/components/slots.html

 

슬롯 | Vue.js

 

v3-docs.vuejs-korea.org

 

// 부모
<FancyButton>
  클릭하기! <!-- 슬롯 컨텐츠 -->
</FancyButton>

// 자식
<button class="fancy-btn">
  <slot>대체텍스트</slot> <!-- 슬롯 아울렛 -->
</button>

// 최종
<button class="fancy-btn">클릭하기!</button>

 

이름 있는 slot

v-slot

#

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


// 부모
<BaseLayout>
  <template #header>
    <h1>다음은 페이지 제목일 수 있습니다.</h1>
  </template>

  <template #default>
    <p>주요 내용에 대한 단락입니다.</p>
    <p>그리고 또 하나.</p>
  </template>

  <template #footer>
    <p>다음은 연락처 정보입니다.</p>
  </template>
</BaseLayout>


// 최종
<div class="container">
  <header>
    <h1>다음은 페이지 제목일 수 있습니다.</h1>
  </header>
  <main>
    <p>주요 내용에 대한 단락입니다.</p>
    <p>그리고 또 하나.</p>
  </main>
  <footer>
    <p>다음은 연락처 정보입니다.</p>
  </footer>
</div>