前端基础之全局事件总线
用于实现任意组件中的通信,我们可以将数据放入到Vue原型中,这样就能实现vc与vm都能访问该数据
我们需要一个能使用去使用$on或是$emit这里方法的东西,vc与vm都能调用这个方法,
但是vm与vm最终在创建时都需要去寻找Vue的原型对象,所以说我们可以直接把Vue的原型对象当作是这个中间人bus
在beforeCreate中我们就能去申明这个中间人
将Student.vue中的信息发送给School.vue中
在main.js中
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 //安装全局事件总线
}
})
在Student.vue中
<template>
<div class="demo">
<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>
.demo{
background-color: orange;
}
</style>
在School.vue中
<template>
<div class="demo">
<h2 >学校名称:{{name }}</h2>
<h2>学校地址:{{addr}}</h2>
</div>
</template>
<script>
export default {
name:'School',
data(){
return{
name:'尚硅谷atguigu',
addr:'北京'
}
},
mounted(){
this.$bus.$on('hello',(data)=>{
console.log('我是School组件,我收到了数据',data)
})
},
beforeDestroy(){
this.$bus.$off()
}
}
</script>
<style scoped>
.demo{
background: skyblue;
}
</style>
我们就实现了发送端使用$emit定义一个自定义方法,然后给School.vue使用$on来进行接收