Trouble with Vue: Sibling components unable to communicate

I am encountering an issue while trying to pass data from typing.js to ending-page.js within sibling components. Despite my efforts, the emit and event hubs are not functioning as expected. However, emitting from typing.js to the parent component works seamlessly. Since there will be only one additional call in this application, I prefer not to use Vuex unless absolutely necessary - I would like to achieve this with simple emits instead. Here is a snippet of my code:

Parent Component:


    <template>
      <div id = "app">

        <typing v-if = "DynamicComponent === 'typing'" />
        <ending_page v-else-if = "DynamicComponent === 'ending_page'" />

      </div>
    </template>

    <script>

      /* Importing sibling components into parent component */
      import typing from './components/typing/index.vue'
      import ending_page from './components/ending-page/index.vue'

      export default {

        name: 'app',
        components: {
          typing,
          ending_page
        },

        data() {
          return {
            DynamicComponent: "typing",
          };
        },

        methods: {
          updateDynamicComponent: function(evt, data){
            this.DynamicComponent = evt;
          },
        },

      };

    </script>

typing.js:


    import { eventBus } from "../../main";

    export default {

      name: 'app',
      components: {

      },

      data() {
        return {
          input: "",
          TC: "somedata",
          timer: null,
          is_started: false,
          style_preferences: null,
        };
      },

      ICallThisFunctionWhenIWantToEmitSomething: function(evt) {
        this.$root.$emit('eventname', 'somedata');
        this.$emit('myEvent', 'ending_page', this.TC.data);
      }

    };

ending-page.js:


    import { eventBus } from "../../main";

    export default {
      name: 'ending-page',
      components: {},

      data () {
        return {
          data: "nothing",
        }
      },

      computed: {

      },

      props: {

      },

      created: function () {
        this.$root.$on('eventname', function (data) {
            console.log(data)
            this.title = data
            this.$nextTick()
        })
      }

    }
    

Answer №1

This example demonstrates the seamless sharing of data between sibling components.

Children components trigger events that are caught by the parent component, which then passes data back down to the children.

In this scenario, the parent component has a shared property called title among its children. When an event like typing emits the input event, the v-model directive captures it and updates the value on the parent component.

For more information, refer to:

https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow

https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components

Vue.component('typing', {
  props: {
    value: ''
  },
  template: '<button @click="emit">Click to change</button>',
  methods: {
    emit() {
      this.$emit('input', `changed on ${Date.now()}`);
    }
  }
});

Vue.component('ending-page', {
  props: {
    title: ''
  },
  template: '<div>{{ title }}</div>',
});

var app = new Vue({
  el: '#app',
  data() {
    return {
      title: 'unchanged',
    };
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <typing v-model="title"></typing>
  <ending-page :title="title"></ending-page>
</div>

Answer №2

A useful way to handle data sharing in Vue.js is through Vuex. Utilize this by storing the data you wish to share in this.$store.state. For functions, consider using mutations for synchronous tasks and actions for asynchronous operations. Learn more about Vuex here!

Answer №3

I remember reading some advice from Jeffrey Way about creating a global events object for facilitating global communication in Vue. Essentially, you can initialize a new Vue instance and use it as an event bus throughout your application.

window.eventBus = new Vue();

// Emitting events from components:
eventBus.$emit('event', data);

// Listening to events in components:
eventBus.$on('event');

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

Is the jQuery ajax .done() function being triggered prematurely?

Struggling with a problem here. I'm dealing with this code (simplified): var initializeZasilkovna = function () { // Initialize object window.packetery.initialize(); }; // Check if the object doesn't exist if (!window.packetery) { // It ...

Unexpected behavior: Angular post request does not include the expected request body

Embarking on my initial solo Angular project... I am endeavoring to make a post request to my freshly created web service and have implemented the following code: headers = new HttpHeaders( {'Content-Type':'text/plain'} ); l ...

Issues with method invocation in jQuery's .ajax requestI am having

After reading this Stack Overflow post, I now understand how to retrieve a return value from an AJAX call: function GetIsDataReady(input) { $.ajax({ url: "http://www.blah.com/services/TestsService.svc/IsDataReady", ...

Is it necessary for me to master React in order to code with React Native?

As I move on to learning React and/or React Native after mastering Angular, it feels like a natural progression in my development journey. My understanding is that React Native could streamline the process of building Android/iOS native apps within one pr ...

Individual Ajax data

Starting out with javascript, I'm a bit unsure of how to tackle this task. Essentially, I am looking to implement a for loop within the ajax data call, rather than listing each item manually. jQuery(document).ready(function() { ...

Refresh the component data according to the vuex state

In order to streamline my workflow, I am developing a single admin panel that will be used for managing multiple web shops. To ensure that I can keep track of which website I am currently working on, I have implemented a website object in my vuex state. Th ...

The error message UnhandledPromiseRejectionWarning: TypeError: crypto.subtle.digest is throwing an error as it is

Encountering an error message saying "crypto.subtle.digest is not a function" when running unit tests using Jest for a function that utilizes crypto.subtle.digest(), have attempted to resolve the issue while using JSDOM with no success: 1. `[Utilizing J ...

Tips for retrieving data from multiple text boxes in a loop in React js and transmitting it to an API

I am in the process of developing a quiz application where I aim to create multiple question input fields based on the administrator's inputs. For example, if the admin provides 10 questions for the quiz, I will then generate a form within a loop fo ...

The fonts in node.js are not functioning as expected, without displaying any error messages

I'm having trouble implementing custom fonts on my website. Despite following the correct file structure, the fonts do not seem to be loading. My project files are organized in the following manner: https://gyazo.com/5ee766f030290e5b2fa42320cc39f10b ...

In the event that the final calculated total is a negative number, reset it to zero. Inform the user of an error through the use of a prompt dialog box

I'm having trouble getting the grand total to display as 0 when I enter all amounts in positive values and then change the unit prices to negative values. However, it works fine when I only enter negative values throughout. Can someone please help me ...

Retrieve an identifier from a web address and transmit it to the Laravel controller using VueJS

I'm currently facing an issue with submitting a form in my Vue application. The route I am working with is: http://cricketstats.test/en/dashboard/players/z2d4ca09a7/india/941/runs In this URL, the number 941 represents the player's ID. I need to ...

When a text is wrapped by an HTML div using absolute positioning, is there a way to prevent it from wrapping without relying on white space

I have a group of div elements positioned absolutely on the screen. If any div contains content that is too big for the screen, the browser wraps it into multiple lines to fit. However, I do not want this behavior. Instead, I want the overflowing content ...

CSS Challenge: How to crop an image without using its parent container directly

I'm currently facing a complex CSS challenge that I can't seem to solve. I want to create an image controller (two-by-two layout on two lines) that can display: The top-left image in full size, The top-right with horizontal scrolling, The botto ...

Element mysteriously concealed in certain Safari cases, consistently visible in Firefox and Chrome

A new angular application has been developed as a "bounce" page for an upcoming social iOS app currently in public beta. Users have the ability to share their profiles by simply providing a link to the site. If the page is accessed via an iOS device w ...

Tips for splitting JavaScript files into smaller chunks using Vue CLI 3 and the webpack performance object

I recently completed a project using vue cli v3, and after building it, I encountered 2 warnings: Warning: Asset size limit: The following assets exceed the recommended size limit (244 KiB). This could impact web performance. Assets: js/chunk-vendors ...

In Internet Explorer 11, the input event in VueJS may not be triggered upon the first input

I am working with an input HTML element that has @input="onInput" assigned to it. Within the onInput method, I have console log output set up, specifically I am logging event.currentTarget.value. However, I've noticed a strange behavior in IE11 - whe ...

Switch between individual highcharts by selecting or deselecting checkboxes

One of the challenges I am facing involves manipulating multiple scatter plots created with highcharts. I have a list of checkboxes, each labeled to correspond with legend identifiers in the highcharts. My goal is to create a dynamic functionality so tha ...

Utilizing a TypeScript definition file (.d.ts) for typings in JavaScript code does not provide alerts for errors regarding primitive types

In my JavaScript component, I have a simple exporting statement: ./component/index.js : export const t = 'string value'; This component also has a TypeScript definition file: ./component/index.d.ts : export const t: number; A very basic Typ ...

The function "onClick" within an external .js file is being referenced

Just starting to learn Javascript and experimenting with an onClick event for an image in an external .js file using the HTML tag. <script type="text/javascript" src="embed.js"> The code found in "embed.js" is as follows: var image1=new Image(); i ...

What causes the discrepancy in smoothness between the JavaScript animation when offline versus its choppiness when online, particularly on AWS

Recently I delved into game development using HTML5/CSS/JS and embarked on a small project. Check out the game here at this AWS storage link: If you open the game and press SPACE, you'll notice that the ball starts moving with occasional brief pauses ...