5
votes

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.

1
I want to put the initialization codes of each components to the components themselves, I don't want to put them on the main vue instance.Jplus2
Are you thinking of using $on and $emit as explained in the docs?Mahmud Adam
Again I'm pretty new to vue js, can you please give me an example on how to achieve what I want based on my question above? not sure how to implement what I want, showing some code samples is really helpful.Jplus2

1 Answers

6
votes

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.