1 在main.js种挂载全局EventBus
2 Vue.prototype.$EventBus = new Vue()
发送
<script>
export default {
name: "A",
methods:{
sendMsg(){
this.$EventBus.$emit('sendMsg',"这是组件A发送的消息!")
}
}
}
</script>
接收
eventBus使用注意事项: 在$on绑定事件之前先使用$off解绑事项。或者
destroyed() {
this.$EventBus.$off('sendMsg')
}
<script>
export default {
name: "B",
mounted(){
this.$eventBus.$off("sendMsg")
this.$EventBus.$on('sendMsg',(msg)=>{
console.log(msg);//这是组件A发送的消息!
})
},
}
</script>