Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use vm.$on to listen to event emitted from child in vue.js 2.0

Tags:

vue.js

I've been through the vue.js events section on events but it seems to only give examples of how to listen to events using the vm.$on handler within html. Between that and the new changes for 2.0 I'm unsure how to simply transmit a event from child -> parent.

I need to transmit an event because after parent receiving i want to broadcast it to another child.

I'm using single page components, this is my setup:

// parent export default {   mounted: function () {     this.$on('myEvent', function (msg) {     console.log('caught in parent', msg)   });  },  components: {   'child': child,  }, }  // child this.$emit('myEvent', true) 

How can I receive this event on the parent vm please? Note, I don't want to use $on in the html. I want the event receiving logic in the vm where it should be.

Thanks,

like image 654
rix Avatar asked Nov 08 '16 11:11

rix


People also ask

How do you emit event from child to grandparent in Vue?

To emit event from grandchild to his grandparent component with Vue. js, we call $emit in the grand child component. Then in the parent component, we pass the events from the child to the grandparent with v-on="$listeners . And then we listen to the event emitted from the grandchild component in the grandparent.

How do you access child components at Vue?

To access child component's data from parent with Vue. js, we can assign a ref to the child component. And then we can access the child component data as a property of the ref. to assign the markdown ref to the markdown component.

How do you access a root component from a child instance in Vue?

Conclusion. We can access the root Vue instance with $root , and the parent component with $parent . To access a child component from a parent, we can assign a ref with a name to the child component and then use this. $refs to access it.


1 Answers

Vues documentation on $emit is not very comprehensive, however, there are a few ways to do this. Firstly you have to $emit on the vue model you want to send the message to if you want to use this.$on(), so if you are sending from a component you can emit to the direct parent using:

this.$parent.$emit('myEvent',true); 

However, this can become problematic if you have a long chain of parents because you have to $emit up the child chain, so in that case you can use a Vue instance as a bus:

// In the root as a global variable so all components have access var bus = new Vue({}); 

Or if you are using single file components.

window.bus = new Vue({}); 

Then in the receiver:

bus.$on('myEvent',() => {    // Do stuff }); 

And in the emitter:

bus.$emit('myEvent',true); 

Finally, if you find you app getting too complex for a simple bus then you can use vuex:

https://vuex.vuejs.org/en/index.html

like image 63
craig_h Avatar answered Sep 20 '22 07:09

craig_h