완벽하게 Vue.js
[Vue.js][Ch2][Vue 문법] 컴포넌트 - Slot
써치킴
2022. 4. 18. 21:49
컴포넌트를 사용할 때
Content를 삽입하면 slot 태그가 대체돼서 내부 Content가 사용되고
Content가 없으면 대신해서 slot 태그 사이에 있는 기본적인 내용이 출력된다.
(이 때, slot 태그를 Fallback contents라고 한다.)
이름을 갖는 슬롯(Named Slots)
slot 태그에 name 속성을 통해서 위치를 지정할 수 있다.
App.vue
<template>
<MyBtn>
<template v-slot:text><span>Banana</span> </template>
<template #icon><span>(B)</span> </template>
</MyBtn>
</template>
<script>
import MyBtn from '~/components/Ex16_MyBtn'
export default {
components: {
MyBtn
}
}
</script>
MyBtn.vue
<template>
<div class="btn">
<slot name="icon"></slot>
<slot name="text"></slot>
</div>
</template>
<style scoped lang="scss">
.btn {
display: inline-block;
margin: 4px;
padding: 6px 12px;
border-radius: 4px;
background-color: gray;
color: white;
cursor: pointer;
&.large {
font-size: 20px;
padding: 10px 20px;
}
}
</style>
template 태그 안의 내용을 각 slot 태그에 표출시키고 name 속성을 통해 위치를 지정할 수 있다.
App.vue에선 text 템플릿이 위에 있지만 MyBtn.vue에선 text 슬롯이 밑에 있기 때문에 Banana는 뒤에 출력된다.
v-bind → :
v-on → @ 약어처럼
v-slot → # 으로 사용할 수 있다.