最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Executing child method from parent component in Vue.js - Stack Overflow

programmeradmin4浏览0评论

Currently, I have a Vue.js ponents which contains a list of other ponents. I know that the mon 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 ponents when a button in the parent is clicked. Which would be the best way to do it?

Currently, I have a Vue.js ponents which contains a list of other ponents. I know that the mon 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 ponents when a button in the parent is clicked. Which would be the best way to do it?

Share Improve this question asked Nov 28, 2016 at 23:41 angrykoalaangrykoala 4,0648 gold badges35 silver badges59 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

One suggested way is to use a global event hub. This allows munication between any ponents 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 ponent.

var eventHub = new Vue();

Vue.ponent('child-ponent', {
  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./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-ponent></child-ponent>
</div>

Here is a simple one which worked for me

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

You can create below helper method in methods in your parent ponent:

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

And call child ponent method in this way:

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

I don't test it for Vue>=2.0

发布评论

评论列表(0)

  1. 暂无评论