一、全局事件總線
1.第一步,安裝全局事件總線(main.js中)
new Vue({
......
beforeCreate() {
Vue.prototype.$bus = this //安裝全局事件總線,$bus就是當(dāng)前應(yīng)用的vm
},
......
})
2.第二步,使用全局事件總線
A組件想接收數(shù)據(jù),則在A組件中給$bus綁定自定義事件,事件的回調(diào)留在A組件自身。
A組件:
<script>
<!--提供數(shù)據(jù)-->
this.$bus.$emit('xxxx',數(shù)據(jù))
</script>
B組件:
<!--接收數(shù)據(jù)-->
mounted() {
this.$bus.$on('xxxx',this.demo)
},
<!--解綁事件-->
beforeDestroy() {
this.$bus.$off('hello')
}
實(shí)例:

image.png

image.png
二、消息訂閱與發(fā)布(在React中框架中用的較多,vue用的較少)
1.第一步,安裝pubsub:npm i pubsub-js
2.第二步,引入(子組件): import pubsub from 'pubsub-js'
3.第三步,接收數(shù)據(jù):A組件想接收數(shù)據(jù),則在A組件中訂閱消息,訂閱的回調(diào)留在A組件自身。
4.代碼實(shí)現(xiàn):
A組件:
import pubsub from 'pubsub-js'
mounted() {
this.pid = pubsub.subscribe('xxx',this.demo) //訂閱消息
}
B組件:
import pubsub from 'pubsub-js'
<!--提供數(shù)據(jù)-->
pubsub.publish('xxx',數(shù)據(jù)),
<!--取消訂閱-->
beforeDestroy() {
pubsub.unsubscribe(this.pubId)
},
實(shí)例:

image.png

image.png