Event Bus
When we're looking to create an application wide events system (that is, without strictly parent to child component), we can create what's known as an Event Bus. This allows us to "pipe" all of our events through a singular Vue instance, essentially allowing for communication past just parent and child components. As well as this, it's useful for those not looking to use third-party libraries such as Vuex
, or smaller projects that are not handling many actions. Let's make a new playground project to demonstrate it:
# Create a new Vue project $ vue init webpack-simple vue-event-bus # Navigate to directory $ cd vue-event-bus # Install dependencies $ npm install # Run application $ npm run dev
Start off by creating an EventsBus.js
inside the src
folder. From here we can export a new Vue instance that we can use to emit events like before with $emit
:
import Vue from 'vue'; export default new Vue();
Next, we can create our two components, ShoppingInput
and ShoppingList
. This will allow...