[Vue] custom event (부모 데이터 변경하기) $emit()
[Vue] custom event (부모 데이터 변경하기) $emit()
자식 컴포넌트에서 props를 수정하고 싶으면 custom event를 사용한다.
자식 컴포넌트에서 부모 컴포넌트로 메세지를 보내
부모 컴포넌트에 있는 데이터를 수정해야 한다.
자식 컴포넌트에서 부모 컴포넌트로 메시지를 보내고,
부모 컴포넌트에서 메시지를 수신해야 한다.
$emit(‘작명’, 데이터)
자식 컴포넌트에서 부모 컴포넌트로 메세지를 보내는 문법
1
2
<!-- <h4 @click="$emit('작명', 데이터)">{{ 원룸.title }}</h4> -->
<h4 @click="$emit('openModal', 원룸.id)">{{ 원룸.title }}</h4>
@작명=”script”
부모 컴포넌트에서 메시지를 수신하는 문법
1
2
<!-- <ProductCard @openModal="모달창열렸니=1" v-for="(a,i) in 원룸들" :key="i" :원룸="원룸들[i]" /> -->
<ProductCard @openModal="모달창열렸니=1; 누른거=$event;" v-for="(a,i) in 원룸들" :key="i" :원룸="원룸들[i]" />
함수사용하기
ProductCard.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div>
<img :src="원룸.image" class="room-img">
<h4 @click="함수">{{ 원룸.title }}</h4>
<p>{{ 원룸.content }}</p>
<p>{{ 원룸.price }}원</p>
</div>
</template>
<script>
export default {
name: 'ProductCard',
props: {
원룸: Object,
},
methods: {
함수(){
this.$emit('openModal', this.원룸.id);
}
}
}
</script>
모달창 닫기
ModalDetail.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
<div class="black-bg" v-if="모달창열렸니==1">
<div class="white-bg">
<img :src="원룸들[누른거].image" class="room-img">
<h4>{{ 원룸들[누른거].title }}</h4>
<p>{{ 원룸들[누른거].content }}</p>
<p>{{ 원룸들[누른거].price }}</p>
<button @click="closeModal">닫기</button>
</div>
</div>
</template>
<script>
export default {
name: 'ModalDetail',
props: {
원룸들: Object, // Number, String, Array
누른거: Number,
모달창열렸니: Number,
},
methods: {
closeModal(){
this.$emit('closeModal');
}
}
}
</script>
<style>
/* modal */
.black-bg{position:fixed; padding:20px; width:100%; height:100%; background:rgba(0,0,0, 0.5);}
.white-bg{width:100%; background:#fff; border-radius:8px; padding:20px;}
</style>
App.vue
1
<ModalDetail :원룸들="원룸들" :누른거="누른거" :모달창열렸니="모달창열렸니" @closeModal="모달창열렸니=0;" />
This post is licensed under CC BY 4.0 by the author.