1. 定義
消息訂閱與發(fā)布是一種組件間通信的方法烂斋。適用于任意組件。
pubsub 是由兩個單詞組成:publish 和 subscribe 發(fā)布和訂閱拔鹰。
設(shè)計思路:訂閱者可以理解為接收數(shù)據(jù)的組件寄疏,發(fā)布者理解為提供數(shù)據(jù)的組件伴榔。在訂閱者組件里預(yù)定一個消息名,然后是一個回調(diào)函數(shù)海铆;當(dāng)發(fā)布者組件里調(diào)用相同的消息名的時候迹恐,訂閱者的回調(diào)函數(shù)被執(zhí)行。這個過程中實現(xiàn)通信卧斟。
目前第三方由很多庫是可以實現(xiàn)這個功能的殴边,比如 pubsub
2. 使用步驟
- 安裝第三方庫:
npm i pubsub-js
- 引入:
import pubsub from "pubsub-js"
- 接收數(shù)據(jù)的組件:A組件想要接收數(shù)據(jù),則在A組件中訂閱消息珍语,訂閱的回調(diào)留在 A 中
methods(){
demo(data){....}
}
...
mounted(){
this.pid = pubsub.subscribe('xxx',this.demo) //訂閱消息
}
- 提供數(shù)據(jù):
pubsub.publish('xxx', 數(shù)據(jù))
- 最好在
beforeDestroy
·鉤子中锤岸,用pubsub.unsubscribe(pid)
去取消訂閱。
3 案例
說明:兄弟組件 Student, School 和 父級組件 App板乙,現(xiàn)在我們要把Student組件里的 name 數(shù)據(jù)給到 Student 和 App
//App.vue
<script>
//import 引入所有組件
import Student from './components/Student.vue'
import School from './components/School.vue'
import PubSub from 'pubsub-js'
export default {
name: "App", // 給app組建命名為 App
//注冊注冊組件 components: { School,Student },
components: {School,Student},
data(){
return {
msg:"你好啊",
}
},
mounted(){
this.pid = PubSub.subscribe("studentName2", (name,data)=>{
console.log('我是app組件是偷,我收到了發(fā)布者的信息', name,data)
this.msg = this.msg + data
})
},
beforeDestroy(){
PubSub.unscribe(this.pid)
}
}
</script>
//School.vue
<script>
import PubSub from 'pubsub-js'
export default {
name:"School",
data(){
return {
msg2: "尚硅谷",
address:"長安區(qū)"
}
},
mounted(){
this.pid = PubSub.subscribe('studentName1', (name,data)=>{
console.log('我是訂閱組件拳氢,從發(fā)布組件接收到了信息', name,data)
})
},
beforeDestroy(){
PubSub.unsubscribe(this.pid)
}
}
</script>
//Student.vue
<script>
import PubSub from 'pubsub-js'
export default {
name: "Student",
data(){
return {
name: "Jackie",
age:18
}
},
methods: {
//把數(shù)據(jù)給School組件
sendStudentName(){
PubSub.publish('studentName1',this.name)
},
//把數(shù)據(jù)給App組件
sendNameToApp(){
PubSub.publish('studentName2',this.name)
}
}
}
</script>