Vue — 컴포넌트 형제간의 이벤트 주고받기.
1 min readOct 4, 2019
How to pass the data or communicate between sibling components.
first of all, you gotta understand what is the $on and $emit
$emit — event trigger , namely it fire the event. a
a @click.prevent="$EventBus.$emit('click-icon')"
when you click the a tag, ‘click-icon’ fire.
and now, we need something to receive this click-icon event
we use $on! this $on is detect the Event from $emit
this.$EventBus.$on('click-icon', () => {
this.drawer = !this.drawer;
});
you get this? you click → event $emit fire -> event $on receive the event $emit. that’s it!
check this code further below
여기에서 의문. html 에서는 어떻게 하나?
Event를 글로벌 이벤트로 설정한다.
//index.html
window.EventBus = new Vue();
new Vue({
el: '#root',
components: {
'a': a,
'b': b,
'c': c
},//component.js//a component
<li class="modal-toggle" v-for="item in couponList" :key="item.couponId" @click.prevent="toggleModal(item)">
methods:{
toggleModal(item){
console.log('data-', item)
EventBus.$emit('click-icon', item)
}
}//b component
data(){
return{
active: false,
item: [],
}
},
created() {
EventBus.$on('click-icon', (item) => {
this.active = !this.active;
this.item = item;
console.log('active', this.active)
console.log('item', this.item)
});
},
# ref
https://alligator.io/vuejs/global-event-bus/
http://wiki.sys4u.co.kr/pages/viewpage.action?pageId=8553499