Use vm.$on to listen to event emitted from child in vue.js 2.0 -
i've been through vue.js events section on events seems give examples of how listen events using vm.$on handler within html. between , new changes 2.0 i'm unsure how transmit event child -> parent.
i need transmit event because after parent receiving want broadcast child.
i'm using single page components, 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 receive event on parent vm please? note, don't want use $on in html. want event receiving logic in vm should be.
thanks,
vues
documentation on $emit
not comprehensive, however, there few ways this. firstly have $emit
on vue model want send message if want use this.$on()
, if sending component can emit direct parent using:
this.$parent.$emit('myevent',true);
however, can become problematic if have long chain of parents because have $emit
child chain, in case can use vue instance bus:
// in root global variable components have access var bus = new vue({});
or if using single file components.
window.bus = new vue({});
then in receiver:
bus.$on('myevent',() => { // stuff });
and in emitter:
bus.$emit('myevent',true);
finally, if find app
getting complex simple bus can use vuex
:
Comments
Post a Comment