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

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

效果:

pubsub-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>

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-02
  • 2021-10-12
  • 2021-08-08
  • 2021-12-20
  • 2021-10-02
猜你喜欢
  • 2021-04-23
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2021-05-24
  • 2021-11-02
  • 2021-05-22
相关资源
相似解决方案