Mikulew
Mikulew

Reputation: 23

The Global Event Bus & notifications in Vue.js

l am trying to create a global event bus so that two components Parent-Child can communicate with each other. I have searched around; I have read a lot of articles about good pattern of The Global Event Bus, however, I cannot find any solution to my situation. I want to add a notification feature in my application. This is a file event.js which there are different types of notifications:

Event.js

import Vue from 'vue';

export default new Vue({
methods: {
    notifySuccess(message) {
        this.$emit('notify', 'success', message);
    },

    notifyInfo(message) {
        this.$emit('notify', 'info', message);
    },

    notifyWarning(message) {
        this.$emit('notify', 'warning', message);
    },

    notifyDanger(message) {
        this.$emit('notify', 'danger', message);
    },

    requestError(error) {
        if (error.response) {
            this.notifyDanger(error.response.status + ': ' + error.response.statusText);
        }
    },
},
});

A Parent component looks like this

App.vue

<template>
  <router-view></router-view>
</template>

<script>
    import Event from './js/event.js';

    export default {
        name: 'app',
        created() {
            Event.$on('notify', (type, message) => alert(`${type}\n${message}`));
        }
    }
</script>

A Child component looks like this

Header.vue

<template>
   <a class="navbar-brand" href="#" @click.prevent="clickTest"></a>
</template>

<script>
    name: 'header',
    methods: {
        clickTest() {
             Event.$emit('notify', 'success', 'Hello World!');
           }
    }
</script>

I will add in the future pop-ups for example notifySuccess displays a pop-up in green color, notifyDanger in red color, notifyWarning in yellow.

How to create an event/method in the Child component in depends of type of nostrification? What am I doing wrong?

PS: Sorry for my bad English. I hope you understand me.

Upvotes: 2

Views: 1927

Answers (1)

choasia
choasia

Reputation: 10852

Replace Event.$emit('notify', 'success', 'Hello World!'); with Event.notifySuccess('Hello World');(You defined methods in Event.js but didn't use them)
And try to avoid using built-in or reserved HTML elements as component id (like header)
Then your code will work without any problem.
See updated demo.

Upvotes: 2

Related Questions