在Vue.js中从父组件执行子方法

时间:2016-11-28 23:41:06

标签: javascript vue.js

目前,我有一个Vue.js组件,其中包含其他组件的列表。我知道使用vue的常用方法是将数据传递给子节点,并从子节点向父节点发送事件。

但是,在这种情况下,我想在单击中的按钮时在子组件中执行方法。哪种方法最好?

3 个答案:

答案 0 :(得分:4)

一种建议的方法是使用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>

答案 1 :(得分:1)

这是一个适合我的简单

this.$children[indexOfComponent].childsMethodName();

答案 2 :(得分:0)

您可以在父组件的方法中创建以下辅助方法:

getChild(name) {
    for(let child of this.$children) if (child.$options.name==name) return child;
},

以这种方式调用子组件方法:

this.getChild('child-component-tag-name').childMethodName(arguments);

我没有为Vue&gt; = 2.0

测试它
相关问题