데일리 공부 기록
hands on vue - slot에 대해 더 알아보자
탐훈
2023. 3. 10. 00:15
728x90
[목표]
1. slot을 설정했는데 만약 슬롯이 없다면 어떻게 될까?
slot을 설정했는데 slot 부분이 없다면 렌더링을 할까?
slot을 설정했는데 없다면 if문으로 분기 태워서 넘어가게 할 수 있을까?
키워드
- <template #header>
- <header v-if="$slots.header">
- console.log(this.$slots.header)
- console.log(this.$slots.header)를 해보았다.
콘솔에는 하나밖에 안찍힌다.
슬롯은 두갠데 ...
왜 하나만 찍힐까
졸려서 힘이없다...
나중에 알아보도록 한다..
UserInfo > BaseCard(자식) 이 있다
자식 컴포넌트에 slot을 해놓았지만
부모 컴포넌트에서 아무것도 설정을 안해도
개발자도구로 확인하면 header부분이 렌더링이 되어있다.
만약 렌더링을 하고싶지 않다면 어떻게 해야할까
v-if를 걸어 부모컴포넌트에 slot 해놓은 아이디가 있는지 없는지 확인한다.
또한 기본값을 걸어줄 수 있다.
아래 코드를 보면 slot를 시켜놨지만
부모 컴포넌트에서 주석을 걸어놨다.
그래서 기본값이 나옴 ..
[UserInfo.vue]
<template>
<base-card>
<!-- <template v-slot:header>
<h3>{{ fullName }}</h3>
<base-badge :type="role" :caption="role.toUpperCase()"></base-badge>
</template> -->
<template v-slot:default>
<p>{{ infoText }}</p>
</template>
</base-card>
</template>
<script>
export default {
props: ['fullName', 'infoText', 'role'],
};
</script>
<style scoped>
section {
margin: 2rem auto;
max-width: 30rem;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
padding: 1rem;
}
section div {
display: flex;
justify-content: space-between;
align-items: center;
}
</style>
[BaseCard.vue]
<template>
<div>
<header>
<slot name="header">
<h2>This is 기본값 </h2>
</slot>
</header>
<slot></slot>
</div>
</template>
<script>
export default {
data(){
return{
}
},
mounted(){
console.log(this.$slots);
},
}
</script>
<style scoped>
div{
margin: 2rem auto;
max-width: 30rem;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
padding: 1rem;
}
</style>