컴포넌트 재사용성을 높여주는 'slot' 에 대해 알아보자.
슬롯은 컴포넌트의 재사용성을 높여주는 기능을 함으로써, 특정 컴포넌트에 등록된 하위 컴포넌트의 마크업을 확정하거나 재정의할 수 있다. 엄격한 부모-자식 관계가 아닌 방법으로 컴포넌트를 구성할 수 있게 해준다.
가장 기본적인 슬롯 사용법에 대해 코드를 통해 알아보자.
// child.vue
<template>
<div class="frame">
<slot></slot>
</div>
</template>
//parent.vue
<template>
<child>
<h1>First Header</h1>
</child>
<child>
<h1>Second Header</h1>
</child>
<child>
<h1>Third Header</h1>
</child>
</template>
이처럼 슬롯을 사용하면 컴포넌트의 특정 마크업 영역을 재정의하여 같은 컴포넌트를 각기 다르게 표현할 수 있다. child 컴포넌트에 slot태그를 정의하지 않았다면 컴포넌트를 등록하는 시점에 마크업을 재정의할 수 없었을 것이다.
앞에서는 개념을 정리하기 위해 1개의 슬롯을 사용했다면 이번에는 더 나아가 여러개의 슬롯을 사용해보자.
여러개의 슬롯을 사용하기위해서는 하나빼고 모두 이름이 필수적으로 필요하다. 이름이 없는 슬롯은 디폴트 값을 가진다.
// button.vue
<template>
<div>
<slot name="title"></slot>
<slot name="content"></slot>
<slot></slot>
</div>
</template>
// buttonContainer.vue
<template>
<button>
<!-- slot 영역 -->
<template>
<h1 v-slot:title>First Header</h1>
<div v-slot:content class="content">Contents #1</div>
</template>
</button>
<button>
<!-- slot 영역 -->
<template>
<h1 v-slot:title>Second Header</h1>
<div v-slot:title class="content">Contents #2</div>
</template>
<template #default>
default slot
</template>
</button>
</template>
'scoped slot'은 컴포넌트 데이터
의 재사용성을 높여주는 기능이다. 일반적으로 뷰에서는 props 속성이나 이벤트 발생과 같은 컴포넌트 통신방법을 제외하고는 다른 컴포넌트의 값을 참조할 수 없다. 하지만 스콥드 슬롯을 이용하면 하위 컴포넌트의 값을 상위 컴포넌트에서 접근하여 사용할 수 있다.
// current-user.vue
<template>
<span>
<slot :user="user"></slot>
</span>
</template>
<script>
export default {
data () {
return {
user: "mong",
}
}
}
</script>
// current-userContainer.vue
<current-user>
<template v-slot:default="props">
<p>{{props.user}}</p>
</template>
</current-user>