자식 구성 요소가있는 기본 Vue 인스턴스가 있다고 가정 해 봅시다. Vue 인스턴스 외부에서 이러한 구성 요소 중 하나에 속하는 메소드를 호출하는 방법이 있습니까?
예를 들면 다음과 같습니다.
var vm = new Vue({
el: '#app',
components: {
'my-component': {
template: '#my-template',
data: function() {
return {
count: 1,
};
},
methods: {
increaseCount: function() {
this.count++;
}
}
},
}
});
$('#external-button').click(function()
{
vm['my-component'].increaseCount(); // This doesn't work
});
<script src="http://vuejs.org/js/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
<my-component></my-component>
<br>
<button id="external-button">External Button</button>
</div>
<template id="my-template">
<div style="border: 1px solid; padding: 5px;">
<p>A counter: {{ count }}</p>
<button @click="increaseCount">Internal Button</button>
</div>
</template>
내부 버튼을 클릭하면 increaseCount()
메서드가 클릭 이벤트에 바인딩되어 호출됩니다. jQuery로 듣고있는 클릭 이벤트 인 외부 버튼에 이벤트를 바인딩 할 수있는 방법이 없으므로을 호출하는 다른 방법이 필요합니다 increaseCount
.
편집하다
이것이 작동하는 것 같습니다 :
vm.$children[0].increaseCount();
그러나 자식 배열의 색인으로 구성 요소를 참조하고 있기 때문에 이것은 좋은 해결책이 아니며 많은 구성 요소를 사용하면 일정하게 유지되지 않고 코드를 읽을 수 없습니다.