①所有的组件都能看到
②能够绑定$on $off$emit 方法
## 全局事件总线(GlobalEventBus)
1. 一种组件间通信的方式,适用于<span style="color:red">任意组件间通信</span>。
2. 安装全局事件总线:
```js
new Vue({
......
beforeCreate() {
Vue.prototype.$bus = this//安装全局事件总线,$bus就是当前应用的vm
},
......
})
```
3. 使用事件总线:
1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的<span style="color:red">回调留在A组件自身。</span>
```js
methods(){
demo(data){......}
}
......
mounted() {
this.$bus.$on('xxxx',this.demo)
}
```
2. 提供数据:```this.$bus.$emit('xxxx',数据)```
4. 最好在beforeDestroy钩子中,用$off去解绑<span style="color:red">当前组件所用到的</span>事件。
School.vue:
<template>
<div class="school">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
export default {
name:'s-school',
data() {
return {
name:'********',
address:'北京·昌平'
}
},
mounted(){
//x指的是vc
//找到x组件,给他绑定了一个hello事件
this.$bus.$on('hello',(data)=>{
console.log('数据:',data)
})
},
beforeDestroy(){
this.$bus.$off('hello')
}
}
</script>
<style scoped>
.school{
background-color: grey;
padding: 5px;
}
</style>
Student.vue:
<template>
<div class="student">
<h2 >学生名称:{{ name }}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">把学生名给School</button>
</div>
</template>
<script>
export default {
name:'s-student',
data() {
return {
name:'Gui',
sex:'female'
}
},
methods:{
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
}
}
</script>
<style scoped>
.student{
background-color: rgb(135, 135, 40);
padding: 5px;
margin-top: 30px;
}
</style>
App.vue:
<template>
<div class="App">
<h1>{{ msg }}</h1>
<School></School>
<Student></Student>
</div>
</template>
<script>
import School from './components/School'
import Student from './components/Student'
export default {
name:'App',
components:{School,Student},
data(){
return{
msg:'你好啊',
}
},
}
</script>
<style scoped>
.App{
background-color: pink;
padding: 5px;
}
</style>