[Vuejs]-Listen emited events of specific child vuejs 2

0👍

You don’t really need a bus. Just emit the event and listen to it from the parent.

console.clear()

Vue.component('dropdown', {
  template: `<button @click="selectedItem">Emit</button>`,
  methods:{
    selectedItem: function(){
      this.$emit('selected-item');
    }
  }
});

Vue.component('some-component', {
  template: `
    <div>
      <h1>Some Component</h1>
      <dropdown @selected-item="onItemSelected"></dropdown>
    </div>`,
  methods:{
    onItemSelected : function(item){
      alert("dropdown b!")
    }
  }
});

new Vue({
  el: '#main-template',
  methods:{
    onItemSelected : function(item){
      alert("dropdown a!")
    }
  }

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="main-template">
      <h1>Main</h1>
      <dropdown @selected-item="onItemSelected" name="dropdown a"></dropdown> 
      <some-component></some-component>
</div>

The above example uses a button in place of whatever you have done for a dropdown, but the principle is the same.

You should only use a bus when there is a specific need. The above snippet should be your default. Emit events from your component, and listen to those events using v-on:some-event (the shortcut for which is @some-event).

👤Bert

Leave a comment