vue进阶篇 - 全局事件总线(GlobalEventBus)

162 阅读2分钟

「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」。


上一篇简单的和大家介绍了关于vue中组件的自定义事件,在本篇我会给大家介绍一下关于vue中组件通信(组件数据传递)的内容这是比较重要也是挺厉害的的一个内容可以叫做全局事件总线(GlobalEventBus)

这个全局事件总线的作用

组件之间的任意沟通和数据传递;

代码演示

下面我将代码贴上,分别使用app.js 和两个组件Student.js School.js完成组件通信;

任意组件通信的方式大家肯定认同一点全部的组件都可以访问到使用我们需要在main里面添加一个可以让所有的组件都可以调用的属性,当然我们不能在源码上加属性,大家应该知道组件实例对象VueComponent(vc)可以访问到 Vue原型上的属性、方法,所有我们就可以通过对vue原型上添加属性、方法来实现:

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

不会的也可以通过某度去查vue和VueComponent关系的方式了解;

下面请看代码演示:

<template>
	<div class="app">
		<h1>{{msg}}</h1>
		<School/>
		<Student/>
	</div>
</template>

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

	export default {
		name:'App',
		components:{School,Student},
		data() {
			return {
				msg:'你好啊!',
			}
		}
	}
</script>

Student.js 和School.js组件:

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

<script>
	export default {
		name:'School',
		data() {
			return {
				name:'VUE大学',
				address:'互联网',
			}
		},
		mounted() {
			// console.log('School',this)
			this.$bus.$on('hello',(data)=>{
				console.log('我是School组件,收到了数据',data)
			})
		},
		beforeDestroy() {
			this.$bus.$off('hello')
		},
	}
</script>
<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:'男孩',
			}
		},
		mounted() {
			// console.log('Student',this.x)
		},
		methods: {
			sendStudentName(){
				this.$bus.$emit('hello',this.name)
			}
		},
	}
</script>

总结

  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去解绑当前组件所用到的事件。