Getting on the event bus bandwagon may sound like a bad idea, you can look up articles with Event Bus in the title and easily find articles that conjure up scary phrases like “anti-pattern” and “avoid at all costs”. Vue.js comes with a built in Event Bus system that really can work wonders if you need to communicate pieces of data across an entire application of uncoupled components.
You can read other articles to further your understanding of life cycles, async data, etc. This article is designed to get you up and running using the awesome abilities of Vue’s Event Bus system.
To start, let’s imagine we have a component, that has some sort of data (in this case a click counter). We want to trigger an emit event in the component that can be utilized globally throughout our app — with no dependency of parent/child state of the components.
Next up — we need to create the
EventBus. This is as simple as creating a new Vue instance which will magically give access to Vue’s internal event bus system.
After that strenuous coding task — we can implement the
EventBus in our
ComponentToEmitEvent component. To do that we will
EventBus and then handle the emit event inside of the click handler in the component.
So right now, we have an
EventBus that is ready to ride, and a component that is ready to get on… we just need a destination. The beauty of the
EventBus is that it doesn’t really matter where we are going. Let’s imagine up some completely unrelated portion of the application that needs access to our super important highly time sensitive click count data.
And just like that we have completed the pipeline. By importing the
EventBus into our component using
EventBus.$on(...),our unrelated component (and you can tell by the component name that it is completely unrelated!) is now hooked into the channel '
global-channel-for-event'and ready to spend its days on the couch watching the clicks go by, ready to tell anyone who will listen how many it has seen.
A few key notes for the road before you grab the wheel of the EventBus and strike out on your own to learn more about this pretty neat Vue ability.
If you only want to listen to a single emission of an event, then you can pass
oncein place of
onduring the EventBus subscription… like so —
If you wish to stop listening after a certain point you could use —
EventBuscould have more than one channel, unlike the TV in the 50’s. If you wish to unsubscribe to all channels from the
EventBusyou can use
EventBus.$off()without passing any arguments.