【Vue基础十】--- 兄弟组件之间传值【中央事件总线,消息订阅与发布】

一、 中央事件总线

1-1 举个栗子

1-1-1 代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>兄弟组件之间传值</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

</head>

<body>
    <div id="root">
        <student></student>
        <hr>
        <hr>
        <hr>
        <school></school>
    </div>
    <script>
        const student = Vue.extend({
            name: 'student',
            template: `
            <div>
              	<h2>学生</h2>
	            <h2>{{age}}</h2>
	            <button @click="sendDataToSch">发送数据给Student组件</button>
            </div>
          `,
            data() {
                return {
                    age: 20
                }
            },
            methods: {
                sendDataToSch() {
                    this.$bus.$emit('stuToSch', 666)
                }
            }

        })
        const school = Vue.extend({
            name: 'school',
            template: `
            <div>
              <h2>学校</h2>
              <h2>{{address}}</h2>
              </div>
          `,
            data() {
                return {
                    address: '山西'
                }
            },

            // 接收 student组件传来的数据
            mounted() {
                this.$bus.$on('stuToSch', (data) => {
                    console.log('我是School组件.我收到了数据', data); //接收的一方完成之后,最好解绑某一个事件
                })
            },
            beforeDestory() {
                this.$bus.$off("stuToSch");
            },
        })

        new Vue({
            el: '#root',
            beforeCreate() {
                Vue.prototype.$bus = this // 安装全局事件总线,$bus就是当前应用的vm
            },
            components: {
                student,
                school
            },

        })
    </script>

</body>

</html>

1-1-2 展示结果

在这里插入图片描述

1-2 中央事件总线详细介绍

任意组件间通信

1-2-1

  1. image-20220726111716358

1-2-2

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

  2. 安装全局事件总线:

    new Vue({
    	......
    	beforeCreate() {
    		Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
    	},
        ......
    }) 
    
  3. 使用事件总线:

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
      }
      
    2. 提供数据:this.$bus.$emit('xxxx',数据)

  4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

二、 消息订阅与发布

2-1 使用方式简介

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

    • 使用步骤:

      1. 安装pubsub:npm i pubsub-js

      2. 引入: import pubsub from 'pubsub-js'

      3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。

        methods(){
          demo(data){......}
        }
        ......
        mounted() {
          this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
        }
        
      4. 提供数据:pubsub.publish('xxx',数据)

      5. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)取消订阅。

2-2 案例展示

  1. School.vue------》 接收数据方

    <template>
      <div>
        <h2>学校地址:{{ address }}</h2>
        <h2 @click="showName">学校名称: {{ name }}</h2>
      </div>
    </template>
    
    <script>
    import pubsub from "pubsub-js";
    // import mixin from "../mixin";
    export default {
      data() {
        return {
          name: "哈哈哈",
          address: "地址",
        };
      },
      mounted() {
        this.pid = pubsub.subscribe("hello", function (e) {
          console.log("有人发布了hello消息,hello消息的回调执行了",e);
        });
      }beforeDestroy() {
     	PubSub.unsubscribe(pid)
     }
    };
    </script>
    
    <style>
    </style>
    
  2. Student.vue------> 发送数据方

    <template>
      <div>
        <h2 @click="showName">学生名称: {{ name }}</h2>
        <h2>学生住址: {{ address }}</h2>
        <button @click="sendStudentName">把学生名给School组件</button>
      </div>
    </template>
    
    <script>
    import PubSub from "pubsub-js";
    // import mixin from "../mixin";
    export default {
      data() {
        return {
          msg: "欢迎学习Vue!",
        };
      },
      mounted() {},
      methods: {
        sendStudentName() {
          PubSub.publish("hello", 888);
        },
      },
      props: ["name", "address"],
    
    };
    </script>
    
    <style>
    </style>
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值