刚开始觉得把页面分成好几个组件会让代码看起来更舒服,但是发现两个组件间很难进行相互通讯,于是发现了全局事件总选可以让组件之间进行相互通讯
1.安装总线
在main.js中:
new Vue({
. . .
beforeCreate() {
Vue.prototype.$bus = this//安装总线
},
. . .
}).$mount('#app')
2.使用总线:
1.接受数据方:
mounted()
{
this.$bus.$on('msg',(data)=>{
this.data=data
})
}
2.发送数据方:
this.$bus.$emit('msg',数据)
3.删除总线:
beforeDestory(){
this.$bus.$off('msg')
}
其中,msg为需要绑定的事件名称,data为接受的数据