2016-11-28 1 views
8

현재 다른 컴포넌트 목록을 포함하는 Vue.js 컴포넌트가 있습니다. 나는 vue로 작업하는 일반적인 방법이 아이들에게 데이터를 전달하고 아이들로부터 부모에게 이벤트를 내보내는 것을 알고 있습니다.Vue.js에서 상위 컴포넌트의 하위 메소드 실행

그러나이 경우 부모의 버튼을 클릭하면 하위 구성 요소에서 메소드를 실행하려고합니다. 가장 좋은 방법은 무엇입니까?

답변

4

제안되는 방법 중 하나는 global event hub입니다. 이렇게하면 허브에 액세스 할 수있는 모든 구성 요소간에 통신 할 수 있습니다.

다음은 이벤트 허브를 사용하여 하위 구성 요소에서 메소드를 시작하는 방법을 보여주는 예입니다. 이 방법으로 아이 컴퍼넌트 방법을

getChild(name) { 
    for(let child of this.$children) if (child.$options.name==name) return child; 
}, 

을 그리고 전화 :

var eventHub = new Vue(); 
 

 
Vue.component('child-component', { 
 
    template: "<div>The 'clicked' event has been fired {{count}} times</div>", 
 
    data: function() { 
 
    return { 
 
     count: 0 
 
    }; 
 
    }, 
 
    methods: { 
 
    clickHandler: function() { 
 
     this.count++; 
 
    } 
 
    }, 
 
    created: function() { 
 
    // We listen for the event on the eventHub 
 
    eventHub.$on('clicked', this.clickHandler); 
 
    } 
 
}); 
 

 
new Vue({ 
 
    el: '#app', 
 
    methods: { 
 
    clickEvent: function() { 
 
     // We emit the event on the event hub 
 
     eventHub.$emit('clicked'); 
 
    } 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script> 
 

 
<div id="app"> 
 
    <button @click="clickEvent">Click me to emit an event on the hub!</button> 
 
    <child-component></child-component> 
 
</div>

+1

'eventHub. $ off ('clicked ', this.clickHandler)'구성 요소를 삭제하기 전에 이벤트 구독을 잊지 말고'beforeDestroy' 라이프 사이클 후크에서 수행 할 수 있습니다 –

0

당신은 당신의 부모 구성 요소에서 방법에 도우미 메서드 이하로 만들 수 있습니다

this.getChild('child-component-tag-name').childMethodName(arguments); 

I을 Vue> = 2.0에 대해 테스트하지 마십시오

관련 문제