Eventbus (이벤트버스)

지금까지는 상위에서 하위 Component로, 하위에서 상위 Component로 데이터를 보냈습니다.
그래서 같은 위치의 Component로 데이터를 보내기 위해서는 상위 Component를 통해서 보내야하지만
EventBus를 활용하면 같은 위치의 Component로 데이터를 보낼 수 있습니다.
사용방법은 emit를 활용하는 방법과 비슷합니다.

상위 Component에서 하위 Component로 데이터 전달

<html>
    <head>
        <title>이벤트 버스를 활용한 데이터 전달</title>
    </head>
    <body>
        <div id="app">
            <child-component></child-component>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.15/dist/vue.min.js"></script>
        <script>
            /* 이벤트 버스 인스턴스 생성 */
            var eventBus = new Vue();
            Vue.component('child-component',{
                template : '<div>하위 컴포넌트 영역입니다. <button v-on:click="showLog">show</button></div>',
                methods : {
                    showLog : function () {
                        eventBus.$emit('triggerEventBus',100);
                    }
                }

            });
            new Vue({
                el : '#app',
                created : function () {
                    eventBus.$on('triggerEventBus', function(value) {
                        console.log("전달받은 값 : ", value);
                    });
                }
            });
        </script>
    </body>
</html>

위 예제에서 EventBus로 사용할 Instance를 하나 생성했습니다.
하위 Component에서는 버튼을 클릭하게 되면 showLog 메소드가 실행됩니다.
showLog 메소드는 상위 Component의 triggerEventBus 이벤트를 실행하고 파라미터로 100을 전달합니다.
상위 Component에서는 created licecycle hook에 $on으로 이벤트를 받는 로직을 선언합니다.
이제 이벤트가 실행되며 콘솔창에 아래와 같은 문구가 출력됩니다.

결과

전달받은 값 : 100

이처럼 EventBus를 활용하면 Component간에도 쉽게 데이터를 주고 받을 수 있습니다.