1

Out of the blue, emitter stopped working:

event-bus.js

import Vue from 'vue';
export const EventBus = new Vue();
import { EventBus } from '../event-bus';

...

mounted() {
  this.getCart();
}

...

methods: {
      getCart() {
        axios.get(`${app.api_erp_url}/cart/${this.cartId}`).then((response) => {
          this.cart = response.data;
          EventBus.$emit('cartLoaded', this.cart); // this not working
        });
      }
},

another-component.vue

mounted() {
      // MiniCart.vue
      EventBus.$on('cartLoaded', (payload) => {
        ...
      });
    },

No matter how I try to emit the event inside mounted/created, it will not work. No problems when firing events on click or something.

Created sandbox: https://codesandbox.io/s/gracious-kilby-m43ih?fontsize=14&hidenavigation=1&theme=dark

tony19
  • 125,647
  • 18
  • 229
  • 307
RomkaLTU
  • 3,683
  • 8
  • 40
  • 63

3 Answers3

3

Child components mount before their parent component.

This is the sequence occurring in your example:

  1. HelloWorld (parent) is created
  2. Test (child) is created
  3. Test (child) is mounted, which emits an event
  4. HelloWorld (parent) is mounted, which subscribes to the event that was already emitted

If you want HelloWorld to catch the event from its children, subscribe to the event in the created hook.

demo

tony19
  • 125,647
  • 18
  • 229
  • 307
1

According to this You should use kebab-case format to name your custom events :

EventBus.$emit('cartLoaded', this.cart);//not correct

EventBus.$emit('cart-loaded', this.cart); //correct
tony19
  • 125,647
  • 18
  • 229
  • 307
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
0

May be the event emitted before MiniCart.vue component registered the event.

Meaning in code.

  EventBus.$emit('cartLoaded', this.cart);

this run first time before the event has been registered

EventBus.$on('cartLoaded', (payload) => {
        ...
      });