Eslam Tahoon
Eslam Tahoon

Reputation: 2323

emit event from slot to grandparen

i have the following scenario:

var grandParend = new Vue({
  components:[parent,child]
  el: '#app',
  template: 
    <parent>
      <child v-on:my-event="eventHandler"><child>
    <parent>
  data: {
    message: 'Hello Vue!'
  },
   methods:{
     eventHandler(){
            // event handler
     }

})

and for child

 Vue.component('child', {
 template: '<button @click="onClick">emit event</button>',
   methods:{ 
     onClick(){
       this.$emit('my-event')
     }

})

how to emit event form child to direct parent? how to emit event form child to grand parent?

thank you

Upvotes: 0

Views: 1645

Answers (1)

Wouter Vandevelde
Wouter Vandevelde

Reputation: 904

You can simply use events to emit events from your child components and handle them in your (grand)-parent.

I made a fiddle to demonstrate with your example: https://jsfiddle.net/oLojabhg/2/

<div id="app">
</div>

var child = Vue.component('child', {
 template: '<button @click="onClick">emit event from child</button>',
   methods:{ 
     onClick(){
       this.$emit('my-event')
     }
   }
})

var grandParend = new Vue({
  components: { parent: parent, child: child },
  el: '#app',
  template: '<parent><child v-on:my-event="eventHandler"></child></parent>',
   methods:{
     eventHandler(){
        console.log('event handled!')
     }
   }
})

Note that you can't actually add listeners to slots, but in most usecases this shouldn't be a problem. More information can be found here:

  1. https://github.com/vuejs/vue/issues/4332
  2. https://github.com/vuejs/vue/issues/4781

Upvotes: 1

Related Questions