vue cli 组件通信传递之$off,$on,$emit

第一步  在mian.js 文件中引入并挂载全局方法

import Vue from 'vue'
/* 挂载全局方法 */
Vue.prototype.$eventBus = new Vue();

 第二部  在需要的监听的文件组件中创建监听方法一般在 mounted 或者 created 挂载监听  这里需要注意方法名字要与 $emit一致

this.$eventBus.$on(方法名字,data =>{
				//监听触发回调
console.log(data); //这里的data就是$emit传递过来的参数
			})

第三步 在需要发送通知的文件组件创建 发送方法

this.$eventBus.$emit(方法名字,参数对象形式)

第四步 监听页面记得页面隐藏或者离开的时候 关闭监听  不然会触发多次 在 beforeDestroy 周期里 添加  $off

beforeDestroy() {
			this.$eventBus.$off(方法名字);
		},

猜你喜欢

转载自blog.csdn.net/qq_37564189/article/details/115330110
今日推荐