简体   繁体   中英

Vue $on event doesn't fire the first time using event bus

I wonder when and why a component can't handle the first $on event that is listening to. I've this function that, when called, fire 2 events:

 initModalTimer: function () {
    serverBus.$emit('initSettingsModal', {
       'name': 'Timer',

    });

    serverBus.$emit('initTimer', {
       'timer_type': this.timer_type,
    });
 }

InitSettingsModal pass info for the modal:

//Modal Component

<template>
<div v-else-if="elementName === 'Timer'">
    <timer></timer>
</div>
<div v-else-if="elementName === 'Socials'">
    <socials></socials>
</div>
</template>

<script>
   //Other Vue stuff
   created() {
      serverBus.$on('initSettingsModal', (elem_identifier) => {
        this.elementName = elem_identifier["name"];
      });
    }
</script>

the second event is handled in the component that is load based on the v-if in the modal component ( in this example is te component timer):

//Timer Component

created() {
     serverBus.$on('initTimer', (response) => {
         //Execute code
     });
}

But the first the 'initTimer' is never fired. When I execute the first function again (initModalTimer) everything work.

I found a similar question on Reddit where someone suggest that "the event bus listen $on is happening after the $emit". But I've not understand what does it mean.

I think what is happening is that your initTimer listener is not registered until your <timer> component is rendered via your v-else-if statement.

You would need to find a way to register that listener before the event is fired, by registering it further up your component tree, or including the timer component earlier, but hiding it from view until it is needed.

Could be a possible solution put the $on event on the function created() . It works for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM