[英]The Global Event Bus & notifications in Vue.js
我正在尝试创建一个全局事件总线,以便两个组件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会以绿色显示弹出窗口,红色会显示NotificationDanger,黄色会显示notifyWarning。
如何根据子类别的类型在子组件中创建事件/方法? 我究竟做错了什么?
PS:对不起,我的英语不好。 我希望你能理解我。
替换Event.$emit('notify', 'success', 'Hello World!');
与Event.notifySuccess('Hello World');
(您在Event.js
定义了方法, Event.js
使用它们)
并尝试避免使用内置或保留的HTML元素作为组件ID(例如header
)
这样您的代码将可以正常工作。
请参阅更新的演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.