Is an Event Bus necessary for sibling communication? Or can a parent send its data as a prop instead?

After watching a tutorial on using an event bus to communicate between sibling components in Vue, I came across an interesting approach. The tutorial demonstrated passing data from a parent component to child components as props, then modifying that prop in one child and using an event bus to pass it onto the other child.

This method got me thinking - why rely on props when each sibling component can have its own data? So, I decided to implement my solution:

main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

export const bus = new Vue() // Event Bus

new Vue({
  render: h => h(App),
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <ComponentA></ComponentA>
    <ComponentB></ComponentB>
  </div>
</template>

<script>
import ComponentA from './components/ComponentA.vue'
import ComponentB from './components/ComponentB.vue'

export default {
  name: 'App',
  components:{
    ComponentA,
    ComponentB
  }
}
</script>

ComponentA.vue

<template>
    <div>
        <h1 @click="changeTitle">Component A</h1>
    </div>
</template>

<script>
import { bus } from '../main'

export default {
    name: 'ComponentA',
    data(){
        return{
            title: ''
        }
    },
    methods:{
        changeTitle(){
            this.title = 'Title emitted from A to B'
            bus.$emit('titleChanged',this.title)
        }
    }
}
</script>

ComponentB.vue

<template>
    <div>
        <h1>Component B -> {{title}}</h1>
    </div>
</template>

<script>
import { bus } from '../main'

export default {
    name: 'ComponentB',
    data(){
        return{
            title: ''
        }
    },
    created(){
        bus.$on('titleChanged', (payload) =>{
            this.title = payload
        })
    }
}
</script>

Does my implementation raise any red flags? Am I missing out on some benefits of using parent data instead of individual component data?

Answer №1

Why it's important for data to originate in the parent and be passed down to children:

  • The reactivity system in Vue.js is centered around having all data stored in one place (a "single source of truth"), then distributing that data as needed. If only one component requires the data, it can be stored within that component. However, when multiple components need the data, storing it in a parent and passing it down to the children is preferable. This becomes especially evident when implementing Vuex.

  • If there is a need to modify, for example, the name of the data (such as changing from title to pageTitle), tracking the data origin becomes much simpler if it always originates from a parent. Relying on an event bus among sibling components can become unreliable as the project scales.

In your scenario, the title should ideally be part of the data in your App.vue component. Each child component would receive it as a prop. Then, if the title needs to be modified, emit an event that App.vue listens for. This event would update the data in App.vue.

For more information, refer to this question:
vuejs update parent data from child component

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery's show/hide function exhibiting inconsistencies when checking or unchecking

I have implemented a feature on my webpage where there is a field for previous surgeries with certain elements. The goal is to display the previous surgery elements only if the "previous surgery" checkbox is checked. Below is a snippet of the code I'm ...

Challenge in WordPress Development

As a beginner in website building, I am looking to customize the background of my pages with a solid color. The current SKT Full Width theme I am using has an opaque background which is causing the text on my slider to blend in and not look appealing. All ...

Experiencing a problem with a loop structure in my code

I've been trying to create a loop that will increase the temperature by 10 degrees every 2 minutes. However, I'm struggling to figure out how to stop the temperature at 120 degrees after 16 minutes. Any suggestions on how to solve this issue? va ...

Effective Strategies for Preserving Form Input Values during Validation Failure in Spring MVC

I am currently working on validating user input, and I want the user's input fields to be retained in case of any validation errors. This is how I have set up my input fields: <form:input path="firstName" class="text short" id="firstName" value=" ...

What steps should I take to modify this Vue.js function?

<script lang="js"> import { ref } from 'vue'; export default { setup(){ const dateInput = ref(new Date()); function handleDateSelection(payload : Date): void { console.log(payload); } return ...

What is the best way to utilize the handlebars-helpers library within an express.js application?

Currently I am using hbs as my template engine in express.js. The handlebars-helpers library from assemble is something that I find extremely useful. However, I am unsure about how to integrate this library into my project. I have also been unable to loca ...

Tips for executing and triggering the same function concurrently from various `<LI>` elements

Is there a way to execute the same function concurrently from multiple <LI> elements using javascript or jQuery? I am looking to utilize the same function with varying parameters to create a tabbed browsing experience. I want multiple tabs to load a ...

What is the correct way to invoke a function contained within an object that is stored in an array?

I've encountered a problem with my program. I'm attempting to invoke a function that is part of an object stored in an array, but I'm having difficulty calling the function correctly. //Initialize Array for Storing Projects let allProjects ...

Ways to retrieve JSON information and incorporate it into an if statement in this specific scenario

Here is the AJAX function code I have written: $('#request_form').submit(function(e) { var form = $(this); var formdata = false; if (window.FormData) { formdata = new FormData(form[0]); } var formAction = form.attr( ...

I'm facing an issue with deploying my Nuxt project on cPanel

I am having difficulties deploying a Nuxt project on cPanel. I would appreciate it if someone could provide me with detailed guidance on how to host it successfully. You can view the images of the errors by clicking on the links below: click here for ima ...

angularJS controller does not seem to be functioning properly due to a certain

var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); var currentdate = yyyy + ',' + mm + ',' + dd; var appointmentDate = moment($scope.AppointmentsList[i].J).f ...

Show the error messages directly beneath each field

Currently, I am utilizing the package found at https://github.com/KuwaitNET/djvue. Despite this specific context, my inquiry pertains to a more general question regarding validation methods. I have crafted the following method to assess the validity of pho ...

Creating a streamlined Vue template rendering experience, free from any unnecessary clutter

I have developed a basic set of Vue components that are currently working well with an existing C# application. Currently, these components are stored as .html files (imported into the app using <script> tags) and .js files loaded by reference. All ...

Guide to Dynamically Including an Element in an Array using Typescript

Encountering a type error within the <RenderFormFields formFields={formFieldsData} /> component:- Types of property 'type' are not compatible. Type 'string' cannot be assigned to type '"select"'.ts(2322) Rende ...

CSS Attribute Selector Wildcard Capture Tool

Suppose I have the following HTML structure: <div class="tocolor-red"> tocolor </div> <div class="tocolor-blue"> tocolor </div> <div class="tocolor-green"> tocolor </div> <div class="tocolor-yellow"> tocolor ...

What is the best way to link an image in a React Component NPM module?

I have developed a date picker component in React and I'm currently working on uploading it to NPM. The component utilizes an external SVG file, but I am encountering issues with referencing that SVG file properly. Here's the structure of my fil ...

Can we utilize v-bind:value or v-model for the data object retrieved from the network?

I am trying to make VueApp use either v-model or v-bind:value for the object received from the network API. For instance, if the Vue app fetches an object from the API in this format: { field1:value1, field2:value2, ......... , field100:value100 } ...

Configuring Visual Studio Publish settings for Single Page Applications deployed on Azure

I have set up my Azure App Service and downloaded the publish profile settings to use FTP for publishing my single page app to Azure. However, I am interested in configuring this process in Visual Studio similar to how one would publish a .Net application ...

Ways to incorporate API data retrieved in Nuxt3 into different methods or functions

How can I effectively utilize data retrieved from an API in Nuxt3? For instance, I am trying to populate meta tags with information fetched from the API, but I keep running into an undefined error. The problem lies in my inability to access pageData withi ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...