How does EventBus
operate?
Communication between components
Any communication between components is available in the instance of Vue
and you can find them by giving console.log(this)
within the component, that is where Props
and EventBus
operate, they simply execute methods on the instance that you yourself could do, but in a much more organized and risky way to say that often even unnecessary ...
EventBus
Before you understand how it works, you need to know if you really need to use it, when it is necessary to execute methods on other components from an action in the central component, we can use EventBus
, it automatically operates on any component that is associated to the component, is $parent
or $children
, it is like a global spread, who wants to hear hears who does not want to be quiet kk ...
In practice
Let's think and a break like this
src
- App.vue
- Propag.vue
- event-bus.js
- main.js
Main will render App.vue
event.bus.js
import Vue from "vue";
export const EventBus = new Vue();
App.vue
<template>
<div>
<div class="pleeease-click-me" @click="emitGlobalClickEvent()">Click para emitir</div>
<Propag ref="prop"></Propag>
</div>
</template>
<script>
import { EventBus } from "./event-bus.js"; // EventBus
import Propag from "./Propag.vue";
export default {
components: { Propag },
data() {
return {
clickCount: 0
};
},
methods: {
emitGlobalClickEvent() {
this.clickCount++;
this.$children[0].somaClickComp(this.clickCount); // Simples
EventBus.$emit("somaClick", this.clickCount); // EventBus
}
}
};
</script>
<style>
div.pleeease-click-me {
width: 130px;
height: 20px;
background: black;
color: white;
display: flex;
align-items: center;
justify-content: center;
padding: 5px;
}
</style>
Propag.vue
<template>
<div class="other">
Atualizado pelo EventBus: {{clicks}} <br>
Atualizado pelo componente : {{compClick}}
</div>
</template>
<script>
import { EventBus } from "./event-bus.js"; // EventBus
export default {
created() { // EventBus
EventBus.$on("somaClick", this.somaClick);
},
data() {
return {
clicks: 0,
compClick: 0
};
},
methods: {
somaClick(item) { // EventBus
this.clicks = item;
},
somaClickComp(item) { // Simples
this.compClick = item;
}
}
};
</script>
<style>
.other {
margin-top: 30px;
width: 250px;
height: 40px;
background: black;
color: white;
display: flex;
align-items: center;
justify-content: center;
padding: 5px;
}
</style>
In the parts where I use EventBus
and the simple method is demarcated with a comment identifying, notice that EventBus
is more verbose and complicated in the long run will help you? in my opinion it only helps to centralize the events, that is, you do not have to worry about pointing the component that will receive the event, just import it, I particularly do not use, because it helps me a lot the practicality and organization of simple communication .
Regarding the second way of doing, I do not know how to speak ...
Rolling code: link