全局事件总线的使用方法

109 阅读1分钟

前言

最近我朋友在学vue,说组件通信好麻烦好难看不懂,所以就萌生出写出这个文章的念头,其实本人也是小白一个,写文章是为了提升自己,另一个是宝宝实在是想要掘金官方的小礼品去装()你懂的,如果写的不好或者哪里有错误还望大家批评指正,废话不多说让我们开始。

介绍

全局事件总线(GlobalEventBus)一种可以在任意组件间通信的方式,本质上就是一个对象,他必须满足以下条件

  • 所有组件对象都必须能看见他(相必大家脑海里第一个想的就是vm)
  • 这个对象必须能够使用$on $emit $off方法去绑定,触发和解绑事件

使用步骤

  1. 在main.js里定义全局事件总线
new Vue({
  ...
  beforeCreate() {
  	Vue.prototype.$bus=this //安装全局事件总线,定义$bus
  }
  ...
})

$bus就是当前应用的vm

  1. 使用全局事件总线
  • [1] 接受数据:A组件想要接受数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
	export default{
		data() {...},
		mounted() {
			this.$bus.$on("xxx",(data)=>{
				console.log("我接收到了数据:",data)
							})
		}
	}
  • [2] 提供数据:
this.$bus.$emit('xxx',data)
  • [3] 解绑当前组件多用到的事件
beforeDestroy() {
		this.$bus.$off('yangyang')
		}

实战了解一下

  1. 在main.js定义全局事件总线
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  beforeCreate() {
  	Vue.prototype.$bus=this //安装全局事件总线,定义$bus
  }
}).$mount('#app')
  1. 创建两个组件,实例在App.vue上
<template>
  <div id="app">
   <SmallMutton></SmallMutton>
   <mutton></mutton>
  </div>
</template>

<script>
import SmallMutton from './components/SmallMutton.vue'
import mutton from './components/mutton.vue'

export default {
  name: 'app',
  components: {
    SmallMutton,
	mutton
  }
}
</script>
  1. 在组件SmallMutton里面定义数据通信
<template>
  <div class="lii">
	 <h4>姓名:{{this.name}}</h4>
	 <h4>性别:{{this.gender}}</h4>
	 <h4>年玲:{{this.age}}</h4>
	 <button @click="yang">点击把name给mutton组件</button>
  </div>
</template>

<script>
export default {
name:"SmallMutton",
  data() {
	  return{
		name:"美羊羊",
		gender:"女",
		age:"88"  
	  }
  },
  methods:{
	  yang(){
		  this.$bus.$emit('yangyang',this.name)
	  }
  }
}
</script>
<style>
	.lii{
		width: 30vw;
		height: 30vh;
		background-color: green;
	}
</style>

  1. 组件mutton接收到数据,显示出来,并且解绑事件
<template>
	<div class="ly">
		<h3>我是mutton组件接收到了数据:{{this.la}}</h3>
	</div>
</template>

<script>
	export default{
		name:"SmallMutton",
		data() {
			return{
				la:""
			}
		},
		mounted() {
			this.$bus.$on("yangyang",(data)=>{
				console.log("我接收到了数据:",data)
				this.la=data
							})
		},
		beforeDestroy() {
			this.$bus.$off('yangyang')
		}
	}

</script>

<style>
	.ly{
		width: 30vw;
		height: 30vh;
		background-color: pink;
	}
</style>

效果展示

image.png