Laravel Vue EventBus vs Props

Laravel Vue EventBus vs Props. When should you use properties and when should you use an EventBus? This is not really a Vue / Laravel issue only, but one you will bump into building your Laravel VueJS app. Here is how one developer I work with approached it with bits and pieces by me.

EventBus

The EventBus is an empty Vue component that resides in the global scope. That is why it can manage event propagation for all components in that global space. If you do not use an EventBus every event will have to be sent from the child component to its parent. And only its direct parent can receive such an event. As the EventBus lives in the global scope all objects including parent and child components can receive events. For our biggest Laravel VueJS project we are mainly using the EventBus for the execution of commands and to keep track of what sidebar tabs are opened and closed.

Loading EventBus

You should create EventBus on app.js before defining Vue components and after importing all the needed JavaScript dependencies. To call the EventBus you could use:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */
require('./bootstrap');
/**
 * Import classes and bind to window for use through the application
 */
import EmptyModule from "./classes/EmptyModule";
/* .......... */
**
* Initialize event bus
*/
window.EventBus = new Vue();

Caveats

Do be careful using it though as it should not replace all child->parent event propagations. Only when you are going up multiple layers it will be useful. This can be the case in a situation when project settings have to be stored in our project. The event is raised in the sidebar, but the root component deals with it.

Props vs EventBus

In most situations where you only deal with single levels and basic child parent communication however, props are a cleaner solution. This way you keep the scope more limited and are therefore more in control over it.

Tagged in : Tagged in : , ,
Jasper Frumau

Jasper has been working with web frameworks and applications such as Laravel, Magento and his favorite CMS WordPress including Roots Trellis and Sage for more than a decade. He helps customers with web design and online marketing. Services provided are web design, ecommerce, SEO, content marketing. When Jasper is not coding, marketing a website, reading about the web or dreaming the internet of things he plays with his son, travels or run a few blocks.