Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventBus in vue not working

I have a Laravel (5.4) application with some Vue components in it. I would need to make some of those components communicate, so I decided to add an EventBus. The code is the following:

app.js:

import VueResource from "vue-resource";
import Vue from "vue";
import Menu from "components/src/core/Menu.vue";

import MapWrapper from "./components/MapWrapper.vue";
import PaymentModal from "./components/PaymentModal.vue";

require("../sass/app.scss");

Vue.use(VueResource);

Vue.component("map-wrapper", MapWrapper);
Vue.component("my-menu", Menu);
Vue.component("payment-modal", PaymentModal);

// eslint-disable-next-line
new Vue({
    el: "#app",
});

event.js:

import Vue from "vue";

const EventBus = new Vue();

export default EventBus;

component that should trigger the event:

<template>
    <div style="height: 100%; width: 100%;">
        <button @click="emitEvent">Click me</button>
    </div>
</template>

<script>
import Vue from "vue";    
import EventBus from "../event";

export default {
    methods: {
        emitEvent() {
            console.log(EventBus);
            EventBus.$emit("testEvent", "test");
        },
    },
};
</script>
<style>
</style>

component that should receive the event:

<template>
    <div>
    </div>
</template>

<script>
import EventBus from "../event";

export default {
    computed: {
        test() {
            EventBus.$on("testEvent", ($event) => {
                console.log("event triggered", $event);
            });
        },
    },
};
</script>

<style>
</style>

The problem is that when I click the button I can see the EventBus logged by the console, but nothing else happen, the receiving components does not catch the event.

What am I missing?

like image 833
ste Avatar asked Dec 13 '22 22:12

ste


1 Answers

You should create EventBus on app.js before defining Vue components.

Vue.use(VueResource);

window.EventBus = new Vue();

Vue.component("map-wrapper", MapWrapper);

Isn't necessary to import EventBus later if using this approach. Just use EventBus.$emit and EventBus.$on everywhere you want!

Hope it helps!

like image 103
Emīls Gulbis Avatar answered Dec 18 '22 06:12

Emīls Gulbis