接下来我就粗略的讲一下如何安装并使用全局事件总线吧!
1.在beforeCreate()这个生命周期钩子中安装全局事件总线
示例代码如下:
new Vue({
el: '#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线
},
})
2。使用全局事件总线
在mounted()这个生命周期钩子中,利用安装好的全局事件总线以及.bus身上绑定事件
示例代码如下:
mounted() {
this.$bus.$on("hello", (data) => {
console.log("学生名交给了学校", data);
});
},
代码分析:绑定的事件名叫hello,当这个事件被触发时,相当于形参,接受触发事件时传过来的参数
3.利用$.emit方法触发事件
示例代码如下:
methods: {
showStudentName() {
this.$bus.$emit("hello", this.name);
}
代码分析:this.name就相当于实参,hello事件被触发
4.销毁这条事件
当你所定义事件的组件已经不再需要时,在beforeDestroy() 这个钩子中利用$.off方法进行销毁,以免造成全局事件总线的压力过大
示例代码如下:
beforeDestroy() {
this.$bus.$off("hello");
},
有了全局事件总线以后,组件之间的通信是不是就就方便了很多呢?