1. 全局事件总线的作用
一种组件间通信方式,适用于任意组件间通信。
2. 安装全局事件总线
new Vue({
......
beforeCreate(){
Vue.prototype.$bus=this //安装全局事件总线,$bus就是当前应用的vm
},
......
})
3. 使用事件总线
接收数据:A组件想接收数据,则在组件A中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){
demo(data){......}
}
......
mounted(){
this.$bus.$on('xxx',this.demo)
}
提供数据:
this.$bus.$on('xxx',数据)
4. 在beforeDestroy钩子中,用$off解绑当前组件所用到的事件
beforeDestroy(){
this.$bus.$off('xxx')
}
5. 样例
main.js
//引入Vue
import Vue from 'vue'
//引入app组件,是所有组件的父组件
import App from './App.vue'
//关闭vue的生产提示
Vue.config.productionTip = false
Vue.config.devtools = true
//创建vue实例对象
new Vue({
//将app组件放入容器中
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线
}
}).$mount('#app')
App.vue
<template>
<div>
<School></School>
<Student></Student>
</div>
</template>
<script>
//引入组件
import Student from './components/Student.vue'
import School from './components/School.vue'
export default {
name:'App',
components:{
Student,
School
}
}
</script>
School.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
export default {
name:'School',
data(){
return {
name:'清华大学计算机专业',
address:'北京'
}
},
mounted(){
this.$bus.$on('hello',(data)=>{
console.log('我是School组件,收到了数据:',data)
})
},
beforeDestroy(){
this.$bus.$off('hello')
}
}
</script>
<style scoped>
.demo{
background-color: skyblue;
}
</style>
Student.vue
<template>
<!-- 组件的结构 -->
<div class="test">
<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('hello',this.name)
}
}
}
</script>
<style scoped>
.test{
background-color: orange;
}
</style>