[TIL] Vue.js 내장 객체-slot

JIEUN YANG·2022년 9월 2일
0
post-thumbnail

내장 객체는 크게 Directives, Components, Special Elements, Special Attributes 로 나뉘며 이번글에서는 driectives의 슬롯에 대해 정리하려 한다.

Slot

1. 역할

slot은 재사용성과 확장성을 위해 사용하며, 상위컴포넌트에서 재정의한 element가 하위컴포넌트의 content로 렌더링 되는 원리이다.

컴포넌트끼리 props로 데이터를 주고 받는 것과 유사하게 템블릿 간 content를 주고 받는다고 생각하면 이해가 좀 더 빠를 것이다.

2. 예시

// Layout.vue

<template>
    <component :is="layout"> 
    	<slot></slot> 
    </component>/>
</template>
  • Layout이라는 하위컴포넌트에 내장 객체 slot을 명시하여 slot위치에 상위에서 정의한 엘리먼트를 랜더링 시킨다.
//App.vue

<template>
  <layout>
    <router-view />
  </layout>
</template>
  • layout컴포넌트 내에 명시한 'router-view'가 slot위치에 렌더링 된다.
  • slot은 text를 비롯하여 모든 HTML 요소가 그 내용이 될 수 있다.

3. Default Slot

slot name은 네이밍해주지 않으면 기본값:default로 지정되며, 상위 컴포넌트에서 name속성과 바인딩 해주지 않아도 default 영역과 매핑된다.

4. Named Slot

// Layout.vue

<template>
  <component :is="layout"> 
  	<slot></slot> 
  </component>/>
  <div>
    <slot name="div-area"></slot>
  </div>
</template>
// App.vue 

<template>
  <layout>
    <router-view />
    <template v-slot:div-area>
    // or  <template #div>
      <span>div-area 영역입니다</span>
    </template>
  </layout>
</template>

특정 위치를 지정하여 엘리먼트를 넘기고 싶다면, slot에 name 속성을 정의하면 된다.
하위 컴포넌트(layout.vue)에 name속성으로 명시된 'div-area' 영역에는 상위 컴포넌트(app.vue)의 "div-area 영역입니다" 라는 요소가 렌더링 되고, 만약 상위 컴포넌트에서 named slot 즉, 아래 요소를 써주지 않으면,

<template v-slot:div-area>
      <span>div-area 영역입니다</span>
    </template>

하위 컴포넌트에서는

<slot name="div-area"></slot>

엘리먼트를 사용하지 않는 것으로 간주하여 렌더링 하지 않는다.

profile
violet's development note

0개의 댓글