A simple EventBus to communicate between Vue.js components
Sometimes you need a quick and easy solution to pass data between Vue.js components.
Of course there's Vuex for centralized state management. Thus on can provide the application with single source of truth.
But for an application with simple architecture it’s enough to communicate between components using events. For this we can create a quick solution and implement EventBus. EventBus allows us to emit an event in one component and listen for that event in another.
This example will show how to do that in Vue.js application. First of all we need a mechanism to transfer events between components. And as it turns out. Because of the simplicity of Vue framework it allows us to create it with few lines of code.
// event-bus.js
import Vue from 'vue';const EventBus = new Vue();export default EventBus;
What’s done here is we created a JavaScript ES6 module which imports Vue and created and exported a new instance of Vue. That’s all. We have implemented the EventBus and can start to use it now.
Here we have a component which imports both Vue and EventBus. When component’s method emitMethod()
gets called, it emits a new event by name EVENT_NAME
and passes a payload along with it.
// component-a.js
import Vue from 'vue';
import EventBus from './event-bus';Vue.component('component-a', {
...
methods: {
emitMethod () {
EventBus.$emit('EVENT_NAME', payLoad);
}
}
});
On another component we can register a listener which listens for event EVENT_NAME
to be transported using EventBus. As soon as event appears we can execute JavaScript with the payLoad
received as an argument.
// component-b.js
import Vue from 'vue';
import EventBus from './event-bus';Vue.component(‘component-b’, {
...
mounted () {
EventBus.$on(‘EVENT_NAME’, function (payLoad) {
...
});
}
});
That's it. Simple as that we have created a solution to transport events between various parts of our application. We can then for example create a new Vue instance for our app or view and start communicate between components.
// app.js
import Vue from 'vue';
import ComponentA form './component-a'
import ComponentB form './component-b';
new Vue({
el: "#app",
components: {
ComponentA,
ComponentB
}
});
In this example we have created and implemented a mechanism to transfer data between loosely coupled components. Without spending a lot of time and effort to learn the principles of Vuex, Redux or other immutable state frameworks. This is a convenient way of communication for simpler architecture. Which can later be upgraded by implementing some centralized state management framework as our app grow. So give it a try and let me know if you have any comments on this.
Are you interested in modern Front-End technologies and would like to work with them daily? Feel free to ping me on Twitter @andrejsabrickis. Or check out our current job opportunities at Mintos. Have a good one!