Communication problems between non-parent and child components of vue.js

Why after clicking send bus.$emit triggers event to send data, there is no response to bus.$on. Then come back and click the button that triggered bus.$emit to print out the console.log (data) result.

this is my trigger button

        test(){
            bus.$emit("OTT","")
        }
        

this is received and written in mounted

  bus.$on("OTT",(value)=>{
            console.log(value)
            //this.tests = value;
        })


Nov.22,2021

are you sure you are using the same bus


I even learned eventbus, now It didn't go wrong after using it for a while.


how bus introduced


this you can see if it helps http://www.cnblogs.com/CccZss.
I used Vue a few months ago and now I don't remember how to communicate.


bus Center Bus's implementation idea is to first register itself globally in main.js, so that every component can access it through this. Because Bus itself is an instance of vue, it has $emit and $on methods, so that we can send and listen to events on the Bus by way of custom events to transmit data, and is not affected by the location of the component.


main.js

const app = new Vue({
    el: '-sharpapp',
    data: {
        eventHub: new Vue()
    },
    render: h=>h(App)
});

component A:

this.$root.eventHub.$emit('something','data')

component B

this.$root.eventHub.$on('something',function(data){
       console.log(data)
})

are you sure the listening component is loaded when sending the message?
check bus.$emit whether mounted > has been executed

before listening to the component .
Menu