【发布时间】:2018-03-13 21:32:26
【问题描述】:
假设我有一个包含子组件的主 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();
但是,这不是一个好的解决方案,因为我通过子数组中的索引来引用组件,并且对于许多组件,这不太可能保持不变并且代码的可读性较差。
【问题讨论】:
-
如果您想尝试一下,我使用 mxins 添加了一个答案。在我看来,我更喜欢以这种方式设置应用程序。
标签: javascript vue.js