IT 라이프
Vue.js 슬롯(Slot) 사용하기 : v-slot 디렉티브
홍삼(HongSam)
2019. 6. 6. 15:27
반응형
Vue.js 2.6.0 버전에서 기존의 named slots와 scoped slots를 통합한 v-slot
이라는 디렉티브가 새로이 소개되었다. v-slot
은 slot
과 slot-scope
어트리뷰트를 대체한다. 이제 slot
과 slot-scope
디렉티브는 Deprecated 상태이다. 앞으로 사라질 예정이니 슬롯을 개발할 때는 v-slot
을 사용하도록 하자.
Named Slots
사용 예시
자식 컴포넌트
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
부모 컴포넌트
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
주의사항
v-slot
디렉티브의 경우, 기존에 사용되던 slot
디렉티브와 다르게 반드시 <template>
태그에 추가되어야 한다.
※ 한가지 예외 사항이 있기는 하다. (Abbreviated Syntax for Lone Default Slots 참조)
Scoped Slots
예시
자식 컴포넌트
<span>
<slot v-bind:user="user">
{{ user.lastName }}
</slot>
</span>
부모 컴포넌트
<current-user>
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</template>
</current-user>
2.6.0 버전에서 새로 추가된 Slots 관련 내용
Dynamic Slot Names
Vue.js 2.6.0 버전에서 새로이 추가된 기능인 Dynamic directive arguments 를 v-slot
에서 사용할 수 있다.
<base-layout>
<template v-slot:[dynamicSlotName]>
...
</template>
</base-layout>
Named Slots Shorthand
v-slot:
대신 #
기호를 사용해서 간단하게 v-slot을 사용 할 수 있다. 예를 들어 v-slot:header
는 #header
로 대체할 수 있다. 자세한 예시를 확인해보자.
<template #header>
<h1>Here might be a page title</h1>
</template>
<current-user #default="{ user }">
{{ user.firstName }}
</current-user>
반응형