Vue——消息的订阅与发布

消息订阅与发布

1.订阅消息∶消息名
2.发布消息︰消息内容

消息订阅与发布的工作流程:
(A是订阅者,B是发布者)
在这里插入图片描述

消息订阅与发布的作用

一种组件间通信的方式,适用于任意组件间通信

消息订阅与发布的实现

需要借助第三方库

这里使用pubsub-js库。

  • 安装:npm i pubsub-js
  • 引入:import pubsub from 'pubsub-js'
  • 订阅者订阅:
    mounted() {
    
    
        // 订阅消息,编写回调函数
        this.pubsubId =  pubsub.subscribe('hello',(msgName,data)=>{
    
    
            console.log(`有人发布了${
      
      msgName}消息,消息内容是:${
      
      data}`)
        })
    },
  • 发布者发布
        sendStudentName() {
    
    
            // 发布事件
            pubsub.publish('hello',666)
        }
  • 订阅者取消订阅
    beforeDestroy() {
    
    
        pubsub.unsubscribe(this.pubsubId)
    }

代码演示

School.vue

<template>
    <div class="demo">
        <h2>学校名字:{
   
   { name }}</h2>
        <h2 class="fonty">地址:{
   
   { address }}</h2>
        <hr>
    </div>
</template>

<script>
import pubsub from 'pubsub-js'
export default {
      
      
    name: 'SchoolVue',
    data() {
      
      
        return {
      
      
            name: "nefu",
            address: "哈尔滨",
        };
    },
    mounted() {
      
      
        // 订阅消息,编写回调函数
        this.pubsubId =  pubsub.subscribe('hello',(msgName,data)=>{
      
      
            console.log(`有人发布了${ 
        msgName}消息,消息内容是:${ 
        data}`)
        })
    },
    beforeDestroy() {
      
      
        pubsub.unsubscribe(this.pubsubId)
  
    }
}
</script>
<style scoped lang="less">
.demo{
      
      
    background: skyblue;
}
</style>

Student.vue

<template>
    <div class="demo">
        <h2>名字:{
   
   { name}}</h2>
        <h2>性别:{
   
   { sex }}</h2>
        <button @click="sendStudentName">把学生姓名给school</button>
        <hr>
    </div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
      
      
    name:'StudentVue',
    data() {
      
      
        console.log(this)
        return {
      
      
            name:"yang123",
            sex:"男"
        }
    },
    methods: {
      
      
        sendStudentName() {
      
      
            // 发布事件
            pubsub.publish('hello',666)
        }
    }
}

</script>
<style scoped>
.demo{
      
      
    background: lightsalmon;
}
</style>

效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mantou_riji/article/details/125897666