Communication between Components

컴포넌트 간에 통신을 하기 위해서는 어떻게 해야 할까?? 기존에 상-하위 구조의 컴포넌트 간에 통신을 위해서는 $emit과 커스텀 이벤트를 통해서 해결 할 수 있었다.

하위 컴포넌트

<template>
	<div>
		<h1>자식 컴포넌트</h1>
		<button @click="btnClick()">클릭!</button>
	</div>
</template>

<script>
	export default {
		methods: {
			btnClick: function(){
				this.$emit('btnClick');
			}		
		}
	}
</script>

상위 컴포넌트

<template>
	<div>
		<h1>부모 컴포넌트</h1>
		<template>
			<child-button @btnClick:"buttonClick()"/>
		</template>
	</div>
</template>

<script>
	import ChildButton from "[경로]/ChildButton";
	export default {
		methods: {
			buttonClick: function(){
				alert('부모에서 이벤트를 받음');
			}		
		}
	}
</script>

상-하위 구조가 아닌 컴포넌트 간에 통신

상-하위 구조가 아닌 컴포넌트에서 통신을 하는 방법 중 위와 비슷한 방식은 main.js에 메인 Vue외에 이벤트 전달용 뷰 객체를 생성하는 것이다.

main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios';
import router from './router'

Vue.prototype.$http = axios;
Vue.config.productionTip = false

/**-------이 부분을 추가-----------**/
export const eventBus = new Vue();
/**------------------------------**/

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

위와 같이 이벤트 전달용 객체를 만든 후 메시지 전달자와 수신자에 아래와 같이 추가한다.

수신자(이벤트를 전달받은 컴포넌트) - ReceiverCompo.vue

<template>
	<div>
				
	</div>
</template>

<script>
	import {eventBus} from "[경로]/main"
	export default {
		data: function(){
			return {
				name: ''
			}
		},
		created(){
			//이벤트 버스에 'hello'라는 메소드가 발생시, 이 부분이 실행될 것이다.
			eventBus.$on('hello',name => {
				this.name = name;
			})
		}
	}
</script>

전달자(이벤트를 발생시킬 컴포넌트) - SenderCompo.vue

<template>
	<div>
		<button @click="hi()"></button>
	</div>
</template>

<script>
	import {eventBus} from "[경로]/main"
	export default {
		methods: {
			hi: function(){
				eventBus.$emit('hello','mojong');
			}
		}
	}
</script>

App.vue

<template>
    <div id="app">
        <receiver-compo></receiver-compo>
        <p>---------------------------------</p>
        <sender-compo></sender-compo>
    </div>
</template>

<script>
    import ReceiverCompo from "[경로]/ReceiveCompo";
    import SenderCompo from "[경로]/SenderCompo";

    export default {
        name: 'app',
        components: {
            ReceiverCompo,
            SenderCompo
        }
    }
</script>

<style>
</style>