$dispatch and $broadcast broadcast and distribute events are deprecated in vue2. Props and $emit () can be used in parent-child components. How to implement communication between non-parent and child components, through instance a Vue instance bus as the medium, to communicate with the sibling components, all introduced bus, and then by invoking bus event triggering and monitoring to achieve communication between components and parameter transfer.
First you need to add a bus.js anywhere
Write the following message inside the Bus.js
1 Import vue from ' Vue ' 2 export default new Vue;
Bus.js is introduced into the components that require communication
If your bus.js is a custom bus file, then the from behind will be changed to your place.
1 import Bus from './bus.js '
The next step is to communicate the components.
Add a trigger #emit的事件按钮
<template> <div id= "emit" >
<button @click = "Bus" > button </button>
</div>
Data () {
return {
Message: ' "
}
},
Export Default {
Methods: { bus () { bus. $emit (' msg ', ' I'm going to pass it to the brother component, you received no ') } }
}
}
Open another component that you want to communicate with $emit add
Listen for MSG events in the hook function
<template> <div id= "on" > <p>{{message}}</p> </div></template> Import Bus from './bus.js ' export default { data () { return { message: ' ' } }, mounted () { Bus. $on (' msg ', (e) = = { This.message = msg })} }
The last P will show the message from $emit.
Vue 2 simple Case for brother (non-parent) component communication using Bus.js