eventBus使用场景: 兄弟组件之间通信
例如有三个组件mainContent, main, head。main组件和head组件在mainContentl里面平级为兄弟组件。
head组件里面有一个输入框点击搜索的时候跳转到main组件并且要带参数过去,这个时候main组件可以在created或者mounted里面获取路由参数进行请求接口。
那么当我们停留在main组件的时候 再次修改了查询条件点击搜索 , 这个时候main组件就无法再次请求接口了 , 因为main组件没有重新加载 , 不会再次触发created和mounted方法。接下来就要用到eventBus
- 创建eventBus
import Vue from 'vue';
const eventBus = new Vue()
export {
eventBus }
- 在使用的组件页面里进行引入
import {
eventBus} from '@/utils/eventBus.js'
- 在head组件中点击搜索使用eventBus触发事件
search(){
//触发事件
eventBus.$emit('search',{
keyWord:this.keyWord,searchType:this.select})
}
- 在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");
},