A. L
A. L

Reputation: 12649

continuously propagate event up chain

If I have nested children that I want to propagate an event all the way up to the root component, is there any simple way to pass on the event?

i.e.

<root @custom_event="doSomething" @another_event="doSomethingElse">
    <child1 @custom_event="passItAlong" @another_event="passItAlong">
        <child2 @custom_event="passItAlong" @another_event="passItAlong">
             <child3 @click="$emit('custom_event', 'data')">
             </child3>
        </child2>
    </child1>
</root>

Upvotes: 0

Views: 74

Answers (1)

Alex Brohshtut
Alex Brohshtut

Reputation: 2060

You have multiple options here:

  1. You can use this.$root.$emit and then event will be sent to all components at once, you can listen to it as this.$root.$on
  2. You can create eventBus as explained here and then use it wherever you need to:
// The most basic event bus

// Imprt vue.js
import Vue from 'vue';

// Create empty vue.js instance to use as event bus
const Bus = new Vue({});

// Export event bus instance
export default Bus;
// Using the most basic event bus

import Vue from 'vue';
import Bus from './basic';

Vue.component('my-first-component', {
  methods: {
    sampleClickAction() {
       Bus.$emit('my-sample-event');
    }
  }
});

Vue.component('my-second-component', {
  created() {
    Bus.$on('my-sample-event', () => {
      // Do something…
    });
  }
});

Upvotes: 1

Related Questions