📌 slot 으로 부모 -> 자식 데이터 전송법
1. 자식은 구멍 뚫기
<slot></slot>
// FilterBox.vue
<template>
<div :style="`background-image : url(${imgUrl})`" :class="`filter-item ${filterNm}`">
<slot></slot>
</div>
</template>
2. <컴포넌트> 태그 사이에 데이터 넣기
// Container.vue
<!-- 필터선택페이지 -->
<div v-if="step === 1">
<div class="upload-image" :style="`background-image: url(${imgUrl})`"></div>
<div class="filters">
<FilterBox :imgUrl="imgUrl" v-for="(filter,i) in filter" :key="i" :filterNm="filter">
데이터~~~
</FilterBox>
</div>
</div>
데이터~~~ 가 <slot></slot> 자리에 들어간다.
필터명을 노출시키고 싶다면
<!-- 필터선택페이지 -->
<div v-if="step === 1">
<div class="upload-image" :style="`background-image: url(${imgUrl})`"></div>
<div class="filters">
<FilterBox :imgUrl="imgUrl" v-for="(filter,i) in filter" :key="i" :filterNm="filter">
{{ filter }}
</FilterBox>
</div>
</div>
- slot 보다 간단하지만
- 태그 안에 데이터바인딩 할 때만 slot 사용 가능하다. (속성에 바인딩 불가) / HTML 태그처럼만 사용 가능
🔹 Named Slots : slot 여러 개 사용하는 법
1. 자식 컴포넌트에서
<slot name="a"></slot>
<slot name="b"></slot>
2. 부모 컴포넌트에서
<template v-slot:a>보낼거</template>
<template v-slot:b>보낼거</template>
이름은 자유작명 가능하다.
slot 개수가 많아지면 코드가 매우 복잡해진다.
🔎 구멍 뚫을 곳이 많으면 (slot 개수가 많아져야 하면) props를 쓰자
slot 으로 html 태그도 전송할 수 있다.
<template v-slot:a><span style="color: red">데이터1</span></template>
<template v-slot:b>데이터2</template>
🔹 slot props
slot 사용할 때 부모가 자식 데이터가 필요한 경우에 쓴다. (별로 쓸 일은 없음)
1. 자식 컴포넌트에서
<slot :자식데이터="자식데이터">
2. 부모 컴포넌트에서
<자식컴포넌트>
<template v-slot:default="작명"> {{작명.데이터}}</template>
</자식컴포넌트>
msg 를 자식 -> 부모 컴포넌트로 전송해보자
// FilterBox.vue (자식 컴포넌트)
data () {
return {
msg: '안녕하세요'
};
}
// Contatiner.vue (부모 컴포넌트)
<FilterBox :imgUrl="imgUrl" v-for="(filter,i) in filter" :key="i" :filterNm="filter">
<template v-slot:a="msg"><span style="color: red">{{msg}}</span></template>
<template v-slot:b>데이터2</template>
</FilterBox>
{{ msg }} 로만 출력하면 다음과 같다.
원하는 메시지 '안녕하세요' 만 출력하려면
{{msg.msg}} 로 출력해야한다.
<div class="filters">
<FilterBox :imgUrl="imgUrl" v-for="(filter,i) in filter" :key="i" :filterNm="filter">
<template v-slot:a="msg"><span style="color: red">{{msg.msg}}</span></template>
<template v-slot:b>데이터2</template>
</FilterBox>
</div>
간단한 props 일 때 slot 을 사용하면 간편하지만, 복잡해지면 props 를 쓰는 것이 좋아보인다.
'Vue3 > 코딩애플 part3' 카테고리의 다른 글
[Vue/코딩애플/part3] 6. vuex 설치 (0) | 2024.08.05 |
---|---|
[Vue/코딩애플/part3] 5. 멀리 있는 컴포넌트간 데이터 전송 시키기(mitt) (0) | 2024.08.05 |
[Vue/코딩애플/part3] 3. tab 만들기 / URL.createObjectURL() (0) | 2024.08.02 |
[Vue/코딩애플/part3] 2. 서버에 ajax 요청하기 (0) | 2024.08.02 |
[Vue/코딩애플/part3] 1. 인스타그램 프로젝트 생성 & 레이아웃 만들기 / style 속성 데이터 바인딩 (0) | 2024.08.02 |