About component communication I believe partners are certainly very familiar with, not to say more, the component communication is not familiar with partners move here. $dispatch and $broadcast are deprecated in Vue2.0. The official document explains:
This is because the event-flow approach based on the component tree structure is difficult to understand and becomes more and more fragile as the component structure expands. This is not a good way of doing things, and we don’t want to cause developers too much pain in the future. Also, $dispatch and $broadcast do not solve the communication problem between sibling components.
The official recommended state management solution is Vuex. However, if the project is not too big and the state management is not too complicated, using Vuex can feel like killing a cat with a knife. Of course, this is also based on your own needs, just suggestions.
The official VUE documentation has this definition: communication between non-parent and child components, which has very little content as follows:
In fact, there is a demo of the non-parent component communication, which is hidden in the migration documentation of $dispatch and $broadcast. If you are interested, you can click on it. The recommendations in the document are:
The easiest way to upgrade $Dispatch and $broadcast is by using an event center that allows components to communicate freely, regardless of which layer they are in the component tree. Since the Vue instance implements an event distribution interface, you can do this by instantiating an empty Vue instance.
This centralized event middleware is the Bus. I’m used to defining bus globally:
app.js
var eventBus = {
install(Vue,options) {
Vue.prototype.$bus = vue
}
};
Vue.use(eventBus);
Copy the code
$emit / $on / $off / $emit / $on / $off / $emit / $on / $off / $emit / $on / $off
Components that distribute events
// ...
methods: {
todo: function () {
this.$bus.$emit('todoSth', params); //params is passed as an argument //... }}Copy the code
Listening component
// ...
created() {
this.$bus.$on('todoSth', (params) => {// get passed parameters and do something //todo something})}, // Preferably before the component is destroyed // clear the event listenerbeforeDestroy () {
this.$bus.$off('todoSth');
},
Copy the code
If you need to listen on multiple components, just change the bus eventName:
// ...
created() {
this.$bus.$on('firstTodo', this.firstTodo);
this.$bus.$on('secondTodo', this.secondTodo); }, // Clear event listenersbeforeDestroy () {
this.$bus.$off('firstTodo', this.firstTodo);
this.$bus.$off('secondTodo', this.secondTodo);
},
Copy the code
If there are any errors or questions, please feel free to share them in the comments.