假设我有一个主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监听其Click事件,因此我需要一些其他方法来调用increaseCount
.
EDIT个
这似乎有效:
vm.$children[0].increaseCount();
但是,这不是一个好的解决方案,因为我是通过组件在子数组中的索引来引用组件的,而且对于许多组件,这不太可能保持不变,代码的可读性也较差.