이벤트 버스
- 최하위에 있는 컴포넌트에서 상위 컴포넌트로 데이터를 전달하려면 버스를 활용하여 데이터를 편리하게 전달할 수 있다.
- 이벤트 버스를 활용하면 props 속성을 이용하지 않고도 원하는 컴포넌트 간에 직접적으로 데이터를 전달 할 수 있어 편리하지만 컴포넌트가 많아지면 어디서 어디로 보냈는지 관리가 되지 않는 문제가 발생. 이 문제를 해결하려면 뷰엑스(Vuex)라는 상태관리도구가 필요하다.
1 2 | // 이벤트 버스를 위한 추가 인스턴스 1개 생성 var eventBus = new Vue(); | cs |
1 2 3 4 5 6 | //이벤트 보내는 컴포넌트 methods : { 메서드명 : function(){ eventBus.$emit('이벤트명', 데이터); } } | cs |
1 2 3 4 5 6 7 8 | //이벤트를 받는 컴포넌트 methods : { created: function(){ eventBus.$on('이벤트명', function(데이터){ ... }) } } | cs |
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 34 35 36 | <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="app"> <child-component></child-component> </div> <script src="https://unpkg.com/vue"></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); } } }); var app = new Vue({ el : '#app', created : function(){ eventBus.$on('triggerEventBus', function(value){ console.log('이벤트를 전달 받음. 전달받은 값 : ', value); }); } }); </script> </body> </html> | cs |
'Vue' 카테고리의 다른 글
네스티드 라우터(Nested Router), 네임드 뷰(Named View) (0) | 2019.08.02 |
---|---|
뷰 라우터 (0) | 2019.08.01 |
props, event emit 컴포넌트의 유효범위 (0) | 2019.07.31 |
css 클래스 바인딩 (0) | 2019.07.31 |
속성값 바인딩하기 (0) | 2019.07.31 |