目前,我有一个Vue.包含其他组件列表的js组件.我知道使用vue的常见方式是将数据传递给子元素,并将事件从子元素发送给家长.

然而,在本例中,当点击parent中的按钮时,我希望在子组件中执行一个方法.哪种方法最好?

推荐答案

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

Vue.js相关问答推荐

Nuxt.js i18n不提供默认区域设置中的页面而不重定向

Nuxt 3 I18N浏览器检测不起作用

有什么理由不在 vue3 中使用