Vue组件通信之“全局事件总线-兄弟组件间的通信”

  1. 一种组件间通信的方式,适用于任意组件间通信。

  2. 安装全局事件总线:

    new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... })

  3. 使用事件总线:

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){ demo(data){......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) }

    2. 提供数据:this.$bus.$emit('xxxx',数据)

  4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

案例展示:

1.在main.js进行安装

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate() {
		Vue.prototype.$bus = this //安装全局事件总线
	},
})

2.student.vue---则在A组件中给$bus绑定自定义事件






3.在school.vue中进行-“获取”-和-“销毁”





你可能感兴趣的:(vue常用,vue.js,javascript,前端,全局事件总线,vue组件通信)