前面很詳細的介紹了子組件與父組件通信 以及 父組件如何與子組件通信
下面將給大家介紹兩種組件間通信的方式,適用于任意組件間通信
全域事件總線
🌟 安裝全域事件總線
new Vue({ .... beforeCreate(){ //安裝全域事件總線 Vue.prototype.$bus = this }, .... })
🌟 使用事件總線
1、接受資料:A組件想接受資料,則在A組件中給$bus系結自定義事件,事件的回呼留在A組件自身
//方法一: methods() { demo(data){....} .... mouted(){ this.$bus.$on('xxx',this.demo) } beforeDestroy() { //在摧毀School組件之前先講傀儡bus解綁 this.$bus.$off("hello"); }, //方法二: this.$bus.$on('xxx',箭頭函式)2、提供資料B組件 this.$bus.$emit('xxx',資料)
最好在beforeDestroy鉤子中,用$off去解綁當前組件最用到的事件
訊息訂閱與發布
安裝 pubsub
npm i pubsub-js
引入 [需要在每個組件中引入]
import pubsub from 'pubsub-js'
接受資料 A組件想接受資料,則在A組件中訂閱訊息,訂閱的回呼函式在A組件自身
//方法一:
methods() {
demo(data){.....}
}
mouted() {
this.pubId = pubsub.subscribe('xxx',this.demo) //訂閱訊息
}
//方法二:
mouted() {
this.pubId = pubsub.subscribe('xxx',(msgName,data)=>{...} ) //訂閱訊息
}
提供資料
pubsub.publish('xxx',資料)
最好在beforeDestroy鉤子中,用PubSub.unsubscribe(subId)去取消訂閱
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/378219.html
標籤:其他
上一篇:Vue 路由(Router)詳細介紹(切換,傳參,通信······)
下一篇:JS 實作兩數之和
