개발팁2018. 12. 14. 16:02

Vue Component 간의 통신하기 위한 방법으로 Event 를 발행하고, Event 를 구독하는 방법을 이용할 수 있다.

 

Vue 이벤트에는 전역이벤트 또는 Global 이벤트가 있고, Component 이벤트 가 있다.

 

 

1. 전역이벤트

 

EventBus 를 통해, 발행하고, 구독할수 있으며,

 

블특정 컴포넌트에서 발행한 이벤트를 구독할 수 있는 형태이다.

 

 

공통의 script 파일안에 전역으로 아래와 같이 선언한다.

 

var EventBus = new Vue();

 

 

EventBus 는 단지, Vue 객체이다.

 

이벤트 발행

 

EventBus.$emit('이벤트명', 전달할 데이터...);

 

이벤트 구독

 

EventBus.$on('이벤트명', function(전달받을 데이터...) { } );

 

사용예제)

 

1. 이벤트발행시

EventBus.$emit("log_class_request", self, findTab.LogClass);

 

2. 이벤트 구독시

EventBus.$on('log_class_request', function (sender, LogClass) {
                self.filter_LogClass = LogClass;
            }); 

 

 

 

2. Component 이벤트

 

컴포넌트 이벤트는 일반적인 언어에서의 이벤트 사용방법과 동일하다.

 

특정 컴포넌트 안에서 이벤트를 발생시키면,

 

해당 컴포넌트를 호출한 부모객체에서 이벤트를 구독하는 방식이다.

 

이벤트 발행

 

this.$emit('이벤트명', 전달할 데이터...);

 

이벤트 구독

 

컴포넌트객체명.$on('이벤트명', function(전달받을 데이터...) { } );

 

 

 사용예제)

 

1. 이벤트발행시

this.$emit('hero_selected', selected_data);

 

2. 이벤트 구독시

self.$children.hero_select = Hero.Select.init(self);  // 컴포넌트 생성


self.$children.hero_select.$on('hero_selected', function (data) {
   ............

});

 

 

Posted by 헝개