Vue 全局事件总线

本文介绍了如何在 Vue.js 应用中使用事件总线(Event Bus)进行组件间的通信。通过创建全局事件总线并在组件的生命周期钩子中绑定和解绑事件,实现了数据在不同组件之间的传递,例如从 Student 组件向 School 组件发送学生名字。这种方法在没有直接父子关系或祖先关系的组件间提供了便捷的数据流动途径。
摘要由CSDN通过智能技术生成

一种可以在任意组件间通信的方式,本质上就是一个对象,它必须满足以下条件

1.所有的组件对象都必须能看见他

2.这个对象必须能够使用$on $emit $off 方法去绑定、触发和解绑事件

在这里插入图片描述
在这里插入图片描述
使用步骤:

1.定义全局事件总线

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

2.使用事件总线

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

export default {
    methods(){
        demo(data){...}
    }
    ...
    mounted() {
        this.$bus.$on('xxx',this.demo)
    }
}

b.提供数据 this. b u s . bus. bus.emit(‘xxx’,data)

3.最好再 beforeDestory 钩子中,用 $off() 去解绑当前组件所用到的事件

src/main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  el:'#app',
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this // 安装全局事件总线
  }
})

src/App.vue

<template>
	<div class="app">
		<School/>
		<Student/>
	</div>
</template>

<script>
	import Student from './components/Student'
	import School from './components/School'

	export default {
		name:'App',
		components:{ School, Student }
	}
</script>

<style scoped>.app{background-color: gray;padding: 5px;}</style>

src/components/School.vue

<template>
  <div class="school">
    <h2>学校名称:{{ name }}</h2>
    <h2>学校地址:{{ address }}</h2>
  </div>
</template>

<script>
  export default {
    name: "School",
    data() {
      return {
        name: "xxxxxxxx",
        address: "北京",
      };
    },
    mounted() {  //🔴
      // console.log('School',this)
      this.$bus.$on("hello", (data) => {
        console.log("我是School组件,收到了数据", data);
      });
    },
    beforeDestroy() {  //🔴
      this.$bus.$off("hello");
    },
  };
</script>

<style scoped>.school {background-color: skyblue;padding: 5px;}</style>

src/components/Student.vue

<template>
  <div class="student">
    <h2>学生姓名:{{ name }}</h2>
    <h2>学生性别:{{ sex }}</h2>
    <button @click="sendStudentName">把学生名给School组件</button> //🔴
  </div>
</template>

<script>
  export default {
    name:'Student',
    data() {
      return {
        name:'张三',
        sex:'男'
      }
    },
    methods: {  //🔴
      sendStudentName(){
        this.$bus.$emit('demo', this.name)
      }
    }
  }
</script>

<style scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}</style>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半夏_2021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值