在Vue.js中从父组件执行子方法 [英] Executing child method from parent component in Vue.js
问题描述
目前,我有一个Vue.js组件,其中包含其他组件的列表。我知道使用vue的常用方法是将数据传递给子节点,并从子节点向父节点发送事件。
Currently, I have a Vue.js components which contains a list of other components. I know that the common way of working with vue is passing data to children, and emitting events to parents from children.
但是,在这种情况下我想执行一个方法单击父级中的按钮时,在子组件中。这是最好的方法吗?
However, in this case I want to execute a method in the children components when a button in the parent is clicked. Which would be the best way to do it?
推荐答案
一种建议的方法是使用全球事件中心。这允许可以访问集线器的任何组件之间的通信。
One suggested way is to use a global event hub. This allows communication between any components that have access to the hub.
这是一个示例,显示如何使用事件中心来触发子组件上的方法。
Here is an example showing how an event hub can be used to fire a method on a child component.
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>
这篇关于在Vue.js中从父组件执行子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!