⚡️ Vue 消息订阅与发布

订阅与发布:一种组件间通信的方式,适用于任意组件之间通信,包含以下操作:

  • 订阅消息:(谁需要谁绑定)对应绑定事件监听
  • 发布消息:(谁提供数据谁发布)分发事件
  • 取消消息订阅:解绑事件监听
image-20220305141518212
  • 使用方式:

    • 在项目中安装第三方库 pubsubJS

      $ npm i pubsub-js
      
      1

      🔗 相关链接: PubSubJS 在线文档 (opens new window)

    • 在入口文件中引入 pubsub

      import pubsub from 'pubsub-js'
      
      1
    • 接收数据: A 组件想接受数据,则在 A 组件中订阅消息,订阅的回调留在 A 组件自身

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
      }
      
      1
      2
      3
      4
      5
      6
      7
    • 提供数据(发布消息,触发订阅的回调函数调用):

      pubsub.publish('xxx', 数据)
      
      1
    • 最好在接收完数据之后,在 beforeDestroy 钩子中用 pubsub.unsubscribe 取消订阅。

🌰 实现消息订阅与发布例子:

(与全局事件总线中 Student 组件将数据发送给 School 类似)

  • 需要数据的组件为 School 组件,所以该组件订阅消息:

    School 组件中引入 pubsub-js

import pubsub from 'pubsub-js'
1

订阅消息:

mounted() {
  /*this.pubid = pubsub.subscribe('hello', function (msgName, data) {
      console.log('有人发布hello消息,hello消息的回调执行了', msgName)
      console.log(this) // undefined
    })*/
    this.pubid = pubsub.subscribe('hello',
                                 )
}
1
2
3
4
5
6
7
8

注意回调函数中的第一个参数为消息名,第二个参数才是接收的数据。

注意

注意此时的 this 指向问题,与自定义事件中的回调函数类似,使用 function 会导致 thisundefined 。此时可以使用在 method 编写回调函数或者使用箭头函数。

  • 在接收完信息后,最好在 beforeDestroy 中取消订阅该消息:
beforeDestroy() {
  // this.$bus.$off('hello')
  pubsub.unsubscribe(this.pubid)
}
1
2
3
4

与自定义事件中解绑事件不一样,要取消订阅不能使用事件名,可以使用在订阅消息以后返回的 pubid 标识该订阅消息。

  • 提供数据的组件 Student 组件发布消息:

    Student 组件中引入 pubsub-js (同上);

    发布消息:

<button @click="sendStudentName">将StudentName发送给School</button>
1
methods:{
  sendStudentName(){
    // this.$bus.$emit('hello', this.name)
    pubsub.publish('hello', this.name)
  }
}
1
2
3
4
5
6

提示

消息的订阅与发布在 Vue 中其实不常用,常用的是在 Vue 中有与此模型相似的全局事件总线。

同时,在 Vue 的开发者工具的事件中能监测到使用的自定义事件,而无法监测来自第三方库的消息订阅与发布。

📢 上次更新: 2022/09/02, 10:18:16