消息訂閱與發(fā)布(pubsub)
? ? 1丽蝎、一種組件間通信的方式,適用于任意組件間通信
? ? 2馒胆、使用步驟:
? ? ? ? ? 1消返、安裝pubsub:? npm i pubsub-js
? ? 3、接受數(shù)據(jù):A組件想接受數(shù)據(jù)劣领,則在A組件中訂閱消息姐军,訂閱的回調(diào)留在A組件自身。
? ? methods(){
? ? ? demo(data){....}
? ? ? ....
? ? ? mounted(){
? ? ? ? ? this.pubId = pubsub.subscribe('xxx',this.demo) //訂閱消息? ? 或者直接在內(nèi)部寫(xiě)成箭頭函數(shù)形式
? ? ? }
? ? }
? ? 4剖踊、提供數(shù)據(jù): pubsub.publish('xxx',數(shù)據(jù))
? ? 5庶弃、最好在beforeDestrory鉤子中,用pubsub.unsubscribe(pubId)去取消訂閱
步驟:
哪個(gè)組件接受數(shù)據(jù) 就在哪個(gè)組件中訂閱消息德澈,訂閱的回調(diào)留在自身。
發(fā)送消息: