Vue3 - slot , v-slot

Kim-Repository·2024년 3월 11일

slot

  • Slot은 부모 컴포넌트에서 자식 컴포넌트의 엘리먼트를 지정할때 사용.
  • 부모에 따라서 자식의 컴포넌트에 영향을 받기 때문에, 컴포넌트 재사용성면에서 좋은 장점을 가진다.

기본사용

<template>
  <!--부모 컴포넌트-->
  <ChildComponent>
    <button>버튼</button>
  </ChildComponent>
</template>


<template>
  <div>
    <!--부모에서 정의한 '버튼'이 위치합니다 -->
    <slot></slot>
  </div>
</template>

이름 있는 슬롯

<template>
  <!--부모 컴포넌트-->
  <ChildComponent>
    <button slot="left">왼쪽 버튼</button>
    <button slot="right">오른쪽 버튼</button>
  </ChildComponent>
</template>

<template>
  <div>
    <!--부모에서 정의한 '왼쪽 버튼'이 위치합니다 -->
    <slot name="left"></slot>

    <!--부모에서 정의한 '오른쪽 버튼'이 위치합니다 -->
    <slot name="right"></slot>
  </div>
</template>
 

자식 데이터 부모에서 사용 하는 slot-scope(함수,변수 모두 사용)


/* 자식 컴포넌트 */
<template>
  <div>
    <header>
      <slot name="child" :childData="childData" :close="close">
        <button>버튼</button>
      </slot>
    </header>
    <div>
      <slot name="body">
        <p>기본 바디</p>
      </slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "BaseModal",
  data() {
    return {
      childData: "child",
      active: false
    };
  },
  methods: {
    close() {
      this.active = false;
    }
  }
};
</script>

/* 부모 컴포넌트*/

<template>
  <div>
    <BaseModal>
      <!--자식에서 사용하던 name="child"로 감싸진 태그의 함수, 변수 모두 가져옵니다.-->
      <template slot="child" slot-scope="slotProps">
        <button @click="slotProps.close">닫기</button>
        <!-- { childData: 'child' } -->
        {{ slotProps }}
      </template>
      <p slot="body">바디입니다.</p>
    </BaseModal>
  </div>
</template>
 

v-slot

  • 간단하게 named-slopt + slot-scope입니다.
  • 다른점은 slot을 v-slot을 사용할 때 무조건 template태그로 감싸고 그 컴포넌트 안에서 v-slot을 사용해야 한다.
<template>
  <div>
    <BaseModal>
      <template v-slot:child="slotProps">
        <button @click="slotProps.close">닫기</button>
        <!-- { hello: 'hello' } -->
        {{ slotProps }}
      </template>
      <template v-slot:body>
        <p>바디입니다.</p>
      </template>
    </BaseModal>
  </div>
</template>

slot , slot-scope는 Vue3에서는 지원하지 않음, Vue3부터는 v-slot을 이용

profile
K - Development Blog

0개의 댓글