其他分享
首页 > 其他分享> > pubsub-js实现消息订阅与发布

pubsub-js实现消息订阅与发布

作者:互联网

官方介绍:https://www.npmjs.com/package/pubsub-js

修改Vue.js全局事件总线(用于任意组件之间的通信)中的例子。

效果:

安装:

npm i pubsub-js

消息订阅者.vue:

<template>
  <div>
      <h1>大儿子</h1>
      <div>收到来自SonaLine的消息:{{msg}}</div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'

export default {
  name: 'SonA',
  data() {
      return {
          msg: '',
      }
  },
  methods: {
      handleMsgFromSonaLine(msgName, data) {
        this.msg = msgName + ': ' + data
      },
  },
  mounted() {
    // this.$bus.$on('SonaLine', this.handleMsgFromSonaLine)
     this.pubId = PubSub.subscribe('SonaLine', this.handleMsgFromSonaLine);
  },
  beforeDestroy() {
    // this.$bus.$off('SonaLine')
    PubSub.unsubscribe(this.pubId);
  },
}
</script>

<style scoped>
    div {
        background-color: aqua;
    }
</style>

消息发布者.vue:

<template>
  <div>
      <h1>小儿子</h1>
      <input v-model="msg">
      <button @click="sendDataToSonA">发数据给大儿子</button>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'

export default {
  name: 'SonB',
  data() {
    return {
      msg: '',
    }
  },
  methods: {
    sendDataToSonA() {
      // this.$bus.$emit('SonaLine', this.msg)
      PubSub.publish('SonaLine', this.msg);
    } 
  },
}
</script>

<style>
    div {
        background-color: yellow;
        margin-top: 20px;
    }
</style>

 

标签:订阅,SonaLine,js,msg,pubsub,data,PubSub
来源: https://www.cnblogs.com/xkxf/p/15877263.html