【发布时间】:2017-04-12 19:58:06
【问题描述】:
目前,我有一个 Vue.js 组件,其中包含其他组件的列表。我知道使用 vue 的常用方式是将数据传递给孩子,并从孩子向父母发出事件。
但是,在这种情况下,当单击 parent 中的按钮时,我想在子组件中执行一个方法。哪种方法最好?
【问题讨论】:
标签: javascript vue.js
目前,我有一个 Vue.js 组件,其中包含其他组件的列表。我知道使用 vue 的常用方式是将数据传递给孩子,并从孩子向父母发出事件。
但是,在这种情况下,当单击 parent 中的按钮时,我想在子组件中执行一个方法。哪种方法最好?
【问题讨论】:
标签: javascript vue.js
这是一个对我有用的简单方法
this.$children[indexOfComponent].childsMethodName();
【讨论】:
您可以在父组件的方法中创建以下辅助方法:
getChild(name) {
for(let child of this.$children) if (child.$options.name==name) return child;
},
并以这种方式调用子组件方法:
this.getChild('child-component-tag-name').childMethodName(arguments);
我没有为 Vue>=2.0 测试它
【讨论】:
一种建议的方法是使用global event hub。这允许可以访问集线器的任何组件之间的通信。
这是一个示例,展示了如何使用事件中心来触发子组件上的方法。
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>
【讨论】:
eventHub.$off('clicked', this.clickHandler)之前不要忘记取消订阅事件,这可以在beforeDestroy生命周期钩子上完成