假设我有一个包含子组件的主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()
方法绑定到其click事件,因此它被调用 . 没有办法将事件绑定到外部按钮,我用jQuery监听其click事件,所以我需要一些其他方法来调用 increaseCount
.
EDIT
这似乎有效:
vm.$children[0].increaseCount();
但是,这不是一个好的解决方案,因为我通过子数组中的索引引用组件,并且对于许多组件,这不太可能保持不变并且代码可读性较差 .
6 回答
这是从其他组件访问组件方法的简单方法
最后我选择使用Vue's ref directive . 这允许从父级引用组件以进行直接访问 .
例如 .
在我的父实例上注册了一个compnent:
使用引用在template / html中渲染组件:
现在,在其他地方我可以从外部访问该组件
看一下这个小提琴的例子:https://jsfiddle.net/xmqgnbu3/1/
(使用Vue 1的旧示例:https://jsfiddle.net/6v7y6msr/)
您可以使用Vue事件系统
和
这是小提琴:http://jsfiddle.net/hfalucas/wc1gg5v4/59/
假设您在子组件中有一个
child_method()
:现在您要从父组件执行
child_method
:如果要从子组件执行父组件方法:
this.$parent.name_of_method()
注意:建议不要像这样访问子组件和父组件 .
相反,作为最佳实践,使用Props&Events进行亲子沟通 .
如果你想要组件之间的通信肯定使用vuex或event bus
请阅读这篇非常有帮助的article
由于Vue2适用于:
//在组件A的方法中
//在组件B的创建钩子中
有关Vue文档,请参阅here . 并且here更详细地介绍了如何准确设置此事件总线 .
如果您想了解何时使用属性,事件和/或集中式状态管理的更多信息,请参阅this article .
这是一个简单的