Javascript 全球事件总线&;Vue.js中的通知
我正在尝试创建一个全局事件总线,以便父子两个组件可以相互通信。我四处寻找;我读过很多关于全球事件总线良好模式的文章,但我找不到任何解决方案。我想在我的应用程序中添加通知功能。这是一个文件event.js,其中有不同类型的通知: Event.jsJavascript 全球事件总线&;Vue.js中的通知,javascript,notifications,event-handling,vuejs2,event-bus,Javascript,Notifications,Event Handling,Vuejs2,Event Bus,我正在尝试创建一个全局事件总线,以便父子两个组件可以相互通信。我四处寻找;我读过很多关于全球事件总线良好模式的文章,但我找不到任何解决方案。我想在我的应用程序中添加通知功能。这是一个文件event.js,其中有不同类型的通知: Event.js import Vue from 'vue'; export default new Vue({ methods: { notifySuccess(message) { this.$emit('notify', 'success'
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>
<template>
<a class="navbar-brand" href="#" @click.prevent="clickTest"></a>
</template>
<script>
name: 'header',
methods: {
clickTest() {
Event.$emit('notify', 'success', 'Hello World!');
}
}
</script>
从“/js/Event.js”导入事件;
导出默认值{
名称:“应用程序”,
创建(){
事件。$on('notify',(type,message)=>alert(`${type}\n${message}');
}
}
子组件如下所示
标题.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>
<template>
<a class="navbar-brand" href="#" @click.prevent="clickTest"></a>
</template>
<script>
name: 'header',
methods: {
clickTest() {
Event.$emit('notify', 'success', 'Hello World!');
}
}
</script>
名称:'标题',
方法:{
单击测试(){
事件。$emit('notify','success','helloworld!');
}
}
我将在以后的弹出窗口中添加,例如notifySuccess以绿色显示弹出窗口,notifyDanger以红色显示弹出窗口,notifyWarning以黄色显示弹出窗口
如何根据nostrification类型在子组件中创建事件/方法?我做错了什么
PS:对不起,我的英语不好。我希望你能理解我。替换事件。$emit('notify','success','helloworld!')代码>带有事件。notifySuccess('Hello World')
(您在Event.js
中定义了方法,但没有使用它们)
并尽量避免使用内置或保留的HTML元素作为组件id(如标题)
然后,您的代码将毫无问题地工作。
看