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

ang*_*ala 8 javascript vue.js

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

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

ase*_*hle 5

一种建议的方法是使用全局事件中心。这允许有权访问集线器的任何组件之间进行通信。

这是一个示例,显示了如何使用事件中心在子组件上激发方法。

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');
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)