vue 组件之间通信eventBus使用方法

eventBus使用场景: 兄弟组件之间通信
例如有三个组件mainContent, main, head。main组件和head组件在mainContentl里面平级为兄弟组件。
head组件里面有一个输入框点击搜索的时候跳转到main组件并且要带参数过去,这个时候main组件可以在created或者mounted里面获取路由参数进行请求接口。
那么当我们停留在main组件的时候 再次修改了查询条件点击搜索 , 这个时候main组件就无法再次请求接口了 , 因为main组件没有重新加载 , 不会再次触发created和mounted方法。接下来就要用到eventBus

  1. 创建eventBus
import Vue from 'vue';
const eventBus = new Vue()
export { eventBus }
  1. 在使用的组件页面里进行引入
import {eventBus} from '@/utils/eventBus.js'
  1. 在head组件中点击搜索使用eventBus触发事件
search(){
//触发事件
	eventBus.$emit('search',{keyWord:this.keyWord,searchType:this.select})
}
  1. 在main组件里面使用mounted调用eventBus监听该事件
//监听事件
mounted(){
    eventBus.$on('search',(data) => {
       this.keyWord = data.keyWord;
       this.select = data.searchType;
       this.search('search')
     })
   },

这样每次点击都会通过eventBus进行监听
注意在main组件销毁前记得关闭监听 , 不然页面没有刷新当你切换到其它组件页面在切换到搜索组件页就会重复进行监听,会执行多次事件

//关闭监听
beforeDestroy(){
   eventBus.$off("search");
 },
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值