[Vue.Js] 8. Vue.Js 컴포넌트간의 통신3
같은 관계와 다른 관계의 예를 같이 알아보는 이유는 동일한 방식으로 하는 것이 더 수월하기 때문입니다.
일단 같은 관계의 경우 부모가 있다면 이전에 배운 방식 두 가지를 사용하여 하위1→상위→하위2 식으로 상위의 관계를 통해 통신을 해야합니다.
이 방식은 같은 부모를 가져야만 가능하기 때문에 별도로 알아보진 않겠습니다.
이번에는 이벤트 버스라는 것으로 통해 통신을 해 볼 것입니다.
그러면 굳이 같은 부모를 가질 필요도 없어지죠.
이번에 쓸 문법은 $emit과 $on입니다만 새로 인스턴스를 생성해서 그 인스턴스의 메소드를 호출해 줄 겁니다.
일단 전체 예제 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Component Comu5</title>
</head>
<body>
<div id="app">
<child-component></child-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js "></script>
<script>
var eventBus = new Vue();
Vue.component('child-component', {
template: '<button v-on:click="child_event">child</button>',
methods: {
child_event: function() {
eventBus.$emit("trigger", "data from child");
}
}
});
new Vue({
el: '#app',
created: function() {
eventBus.$on("trigger", function(data){
alert("parent: "+ data);
})
},
});
</script>
</body>
</html>
양이 많으니 필요한 부분만
설명 드리자면
child-component만 사용됩니다.
아래의 Vue코드를 보시면 eventBus로 사용할 Vue인스턴스를 하나 만들어 준 뒤
이전에 사용했던 것과 흡사하게 template의 v-on:click에는 chilld의 메소드를 등록해주고 그 메소드 안에 $emit을 넣어줍니다.
여기서 다른게 $emit을 위의 eventBus의 $emit을 호출해 줍니다.
첫 번째 매개변수에는 “trigger”를 넣어준 뒤 두 번째 파라미터에 전달할 값(”data from child”)를 넣어주겠습니다.
이벤트를 받는 쪽에서는 created에 eventBus의 $on을 넣어줍니다.
$on쪽도 trigger를 넣고 두 번째 파라미터로 function(받을 변수명){ 실행항 이벤트 내용 } 을 넣어줍니다.
<div id="app">
<child-component></child-component>
</div>
var eventBus = new Vue();
Vue.component('child-component', {
template: '<button v-on:click="child_event">child</button>',
methods: {
child_event: function() {
eventBus.$emit("trigger", "data from child");
}
}
});
new Vue({
el: '#app',
created: function() {
eventBus.$on("trigger", function(data){
alert("parent: "+ data);
})
},
});
그러면 이 예제에서는
child-component의 버튼을 클릭하면 eventBus의 $emit이 호출되고 trigger라는 이벤트를 발생시키고 그 이벤트는 created에 등록했던 event.$on에 입력한 function(data)에 "data from child”를 넣고 해당 로직을 실행 시킵니다.
따라서 아래와 같이 "parent: data from child”라고 알림 창이 뜹니다.
이렇게 eventBus를 통한 통신 방법을 알아봤습니다.
이제 컴포넌트 간 자유롭게 통신하실 수 있을 거라 생각합니다.
되게 편해 보이지만 프로그램의 덩치가 커지면 관리하기 힘들어집니다.
이에 대해서는 나중에 따로 설명 드리겠습니다.