全球事件总线& Vue.js中的通知

时间:2017-08-25 09:34:21

标签: javascript notifications event-handling vuejs2 event-bus

我正在尝试创建一个全局事件总线,以便两个组件Parent-Child可以相互通信。我四处寻找;我已经阅读了很多关于全球事件总线良好模式的文章,但是,我无法找到解决方案。我想在我的应用程序中添加通知功能。这是一个文件event.js,它有不同类型的通知:

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);
        }
    },
},
});

父组件看起来像这样

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>

子组件看起来像这样

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>

我将在以后的弹出窗口中添加例如notifySuccess显示绿色弹出窗口,notifyDanger显示为红色,notifyWarning显示为黄色。

如何在子组件中创建事件/方法取决于nostrification的类型?我做错了什么?

PS:抱歉我的英语不好。我希望你理解我。

1 个答案:

答案 0 :(得分:0)

Event.$emit('notify', 'success', 'Hello World!');替换为Event.notifySuccess('Hello World');(您在Event.js中定义的方法但未使用它们)
并尽量避免使用内置或保留的HTML元素作为组件ID(如header
然后您的代码将毫无问题地工作 请参阅updated demo