Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event custom event from main vue instance, listen from component

Tags:

vue.js

Pretty new to vue js here,

Just want to know if is it possible to emit a custom event from the main vue instance (parent) and the components could listen to that custom event and act accordingly when that event is triggered?

I want to trigger a custom event on vue instance mounted lifecycle function then all components can initialize themselves.

ex.

Main vue instance

new Vue( {
    el : '#main-app',
    mounted : function() {
       this.$emit( 'init-app' );
    }
} );

Then on the various components, it can listen for the 'init-app' custom event then act accordingly when it is triggered or emitted.

Not sure how to do this coz in vue js event listeners are attached to the html tags? can an event listener or a function in a component be triggered by just the emitting of the event from the parent alone?

Note: I'm using vue js 2.0.3 and my components are global, they are not inline

ex.

Vue.component('my-component', {
   template: '#component-template'
});

I could add more components later on.

Thanks in advance.

like image 293
Jplus2 Avatar asked Oct 17 '16 04:10

Jplus2


1 Answers

The correct way to initialize your child components is to use created: life-cycle hook for each of your child components.

Reason: It is quite possible that your child component may not be instantiated when you send your init-app event from the parent component. So, it will never get initialized.

Additional note on events: If you are sending an event from child component to parent component, you should use this.$parent.$emit("my-event-code") and receive it on the parent side as this.$on("my-event-code"). I figured it out recently after hours of trying various methods.

So, if you are trying to send an init-app event from parent to child, you might have to listen on child component as this.$parent.$on("init-app", ...) - I haven't verified this yet, this is my current understanding.

like image 95
Mani Avatar answered Oct 15 '22 05:10

Mani