How to use eventBus for communication between vue components

EventBus usage scenarios: Communication between brother components
For example, there are three components mainContent, main, and head. The main component and the head component are equal to sibling components in mainContentl.
There is an input box in the head component when you click to search, it jumps to the main component and takes parameters. At this time, the main component can obtain routing parameters in the created or mounted to request the interface.
Then when we stay in the main component, we modify the query conditions again and click search. At this time, the main component cannot request the interface again, because the main component is not reloaded, and the created and mounted methods will not be triggered again. EventBus will be used next

  1. Create eventBus
import Vue from 'vue';
const eventBus = new Vue()
export {
    
     eventBus }
  1. Introduce in the component page used
import {
    
    eventBus} from '@/utils/eventBus.js'
  1. Click search in the head component to trigger an event using eventBus
search(){
    
    
//触发事件
	eventBus.$emit('search',{
    
    keyWord:this.keyWord,searchType:this.select})
}
  1. Use mounted in the main component to call eventBus to monitor the event
//监听事件
mounted(){
    
    
    eventBus.$on('search',(data) => {
    
    
       this.keyWord = data.keyWord;
       this.select = data.searchType;
       this.search('search')
     })
   },

In this way, each click will be monitored through eventBus.
Remember to turn off the monitoring before the main component is destroyed, otherwise the page will not refresh. When you switch to other component pages, you will repeat the monitoring when you switch to the search component page, and multiple events will be executed.

//关闭监听
beforeDestroy(){
    
    
   eventBus.$off("search");
 },

Guess you like

Origin blog.csdn.net/weixin_42407989/article/details/111477540