Use vm. $ To listen for the event fired from child in vue.js 2.0

I went through the vue.js events section on events, but it seems to only give examples of how to listen to events using vm. $ on handler inside html. Meanwhile, with the new changes for 2.0, I'm not sure how easy it is to pass the event from child -> parent.

I need to convey the event, because after receiving the parent I want to transfer it to another child.

I use 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 get this event on parent vm, please? Notice I do not want to use $ on in html. I want the event to get the logic in vm where it should be.

Thanks,

+6
source share
1 answer

Vues $emit not very comprehensive, however there are several ways to do this. First, you need $emit in the VUE model for which you want to send a message if you want to use this.$on() , so if you are sending from a component, you can pass it 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 create a child chain, so in this case you can use an instance of Vue as a bus:

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

Or if you are using separate 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 that the app getting too complicated for a simple bus, you can use vuex :

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

+9
source

Source: https://habr.com/ru/post/1012139/


All Articles