1 概述
- 全局事件总线:一种组件间通信的方式,适用于任意组件间通信。
- 原理
- 在Vue的原型对象上添加一个
$bus
属性,属性值为vm(Vue实例对象)。在接受数据的组件里绑定事件,在发送数据的组件里触发事件。这样通过共有属性$bus
实现任意组件间通信。 - 在Vue的原型对象上添加属性的原因:最主要的原因是我们需要将
$bus
能够被任意组件访问。 $bus
属性值为vm的原因:需要$bus
属性能够调用$on
、$off
、$emit
等方法。
- 在Vue的原型对象上添加一个
- 下面我们利用全局事件总线实现任意组件间通信。
2 项目准备
- 创建Vue项目(不会创建Vue项目,请参照Vue项目创建)
- 编写
School
组件
<template>
<div class="school">
<h2>学校信息</h2>
<h3>学校名称:{{name}}</h3>
<h3>学校地址:{{address}}</h3>
<button @click="transmit">点我传递学校名</button>
</div>
</template>
<script>
export default {
name: 'MySchool',
data() {
return {
name: '西昌学院',
address: '西昌'
}
}
}
</script>
<style scoped>
.school {
background-color: green;
}
</style>
- 编写
Student
组件
<template>
<div class="student">
<h2>学生信息</h2>
<h3>学生姓名:{{name}}</h3>
<h3>学生年龄:{{age}}</h3>
<h3>学生性别:{{sex}}</h3>
</div>
</template>
<script>
export default {
name: 'MyStudent',
data() {
return {
name: '奇怪',
age: 19,
sex: '男'
}
}
}
</script>
<style scoped>
.student {
background-color: skyblue;
}
</style>
- 编写
App
组件
<template>
<div>
<School></School>
<Student></Student>
</div>
</template>
<script>
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
name: 'App',
components: {
School,
Student
}
}
</script>
- 我们来看看效果图,下面我们就来实现
School
组件向Student
组件传递学校名称
3 定义全局事件总线
在main.js
文件中添加$bus
属性
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;
}
});
4 定义事件及触发事件
4.1 定义事件
mounted() {
this.$bus.$on('transmitSchoolName', (schoolName) => {
console.log(schoolName);
})
},
beforeDestroy() {
this.$bus.$off('transmitSchoolName');
}
4.2 触发事件
在School
组件里利用按钮传递学校名称
methods: {
transmit() {
this.$bus.$emit('transmitSchoolName', this.name);
}
}