之前写过子组件向父组件传递数据可以使用自定义事件,今天换种方式利用$bus全局事件总线来实现。但是自定义事件传数据只能一级一级传:孙子->父亲->爷爷只是得提前声明一个方法来做,如果孙子只给爷爷传数据的话,其实写起来比较繁琐,但是用全局总线的话直接就可以传递数据。
全局事件总线(GlobalEventBus)
1.一种组件之间通信的方式,适用于任意组件间通信。
2.安装全局事件总线:
main.js
new Vue({
el: '#app',
render: h => h(App),
//安装全局事件总线
//利用全局总线bus实现数据传递 与 watchervue this.$bus.$on呼应 与main.js beforeCreate 呼应
beforeCreate(){
//this就是最外层的new vue({})
//$bus就是当前的vm
Vue.prototype.$bus = this
}
3.使用事件总线
student.vue 提供数据
export default {
//代表组件名称,最好与 school.vue中的school一致
name:'student',
data(){
return{
name:'lj',
sex:'男'
}
},
methods:{
//利用全局总线bus实现数据传递 与 watchervue this.$bus.$on呼应 与main.js beforeCreate beforeDestroy呼应
sendStudentName2(){
this.$bus.$emit('hello',this.sex);
}
}
}
watchvue.vue 接收数据
export default {
//代表组件名称,最好与 school.vue中的school一致
name:'watchvue',
data(){
return{
name:"哈弗",
address:"漂亮国",
msg:"hahh",
msg1111:"ha_yy"
}
},
methods:{
demo(data){.......}
}
mounted(){
//利用全局总线bus实现数据传递 与 watchervue this.$bus.$on呼应 与main.js beforeCreate beforeDestroy呼应
this.$bus.$on('hello',(data)=>{
console.log("我是watchvue组件,利用全局总线实现,收到了student传来的数据",data)
})
//或者
//this.$bus.$on('hello',this.demo)
},
//全局总线用完$bus后你得记得给解绑,不然$bus上面太多了
beforeDestroy(){
this.$bus.$off('hello');
}
}
或者利用上面的methods中的demo方法(回调方法)
this.$bus.$on('hello',this.demo)
4.最好在beforedestory钩子中,用$off去解绑当前组件所用到的事件
//全局总线用完$bus后你得记得给解绑,不然$bus上面太多了
beforeDestroy(){
this.$bus.$off('hello');
}