Vue js parent-child communication using event bus fails to function

Is there any way to successfully communicate between non parent child components in vue js document? I followed the instructions in the vue document, but unfortunately, my code did not work as expected. Below is a snippet of my code:

The structure of the html page:

<html>
  <body>
      <div id="app10">
          <component3 :id="id"></component3>
          <component4 :id="id"></component4>
      </div>
  </body

</html>

The javascript script:

var bus = new Vue();
Vue.component('component3', {
  template: `
    <div @click='change'>
      {{id}}
    </div>
  `,
  props: ['id'],
  methods: {
    change() {
      console.log('??? component3 emit');
      bus.$emit('idSelected', 3);
    }
  },
  mounted() {
  }
});

Vue.component('component4', {
  template: `
    <div>
      {{id}}
    </div>
  `,
  props: ['id'],
});

var app10 = new Vue({
  el: '#app10',
  data: function() {
    return {
      id: '?'
    }
  },
  mounted() {
    bus.$on('idSelected', function(value) {
      console.log('??? app10 click event value: ', value);
      this.id = value;
      console.log('??? this.id', this.id);
    });
  },
  methods: {
  }
});

My goal is to have the text content of 'component3' change from a question mark '?' to 'number 3' when clicked. However, the change is not reflected in the actual output. Despite updating the 'id' in the parent data to '3', the 'id' in the child props remains unchanged. Why is this happening?

The console output shows:

??? component3 emit
??? app10 click event value:  3
??? this.id 3

Answer №1

The issue here relates to scoping. Make a modification to your mounted hook like this:

mounted() {
    const self = this; // saving reference to current 'this'
    bus.$on('idSelected', function(value) {
      console.log('??? app10 click event value: ', value);
      self.id = value; // using 'self' here
      console.log('??? this.id', this.id);
    });
  }

If not, you will lose a reference to the current 'this' because it becomes equal to 'bus' inside your event listener. Check if console.log(this === bus) in your listener ( == true).

Answer №2

Change the way you handle the value of this in your code within the anonymous function. Switch to using an arrow function to maintain the context of your vue instance.

var bus = new Vue();
Vue.component('component3', {
  template: `
    <div @click='change'>
      {{id}}
    </div>
  `,
  props: ['id'],
  methods: {
    change() {
      console.log('??? component3 emit');
      bus.$emit('idSelected', 3);
    }
  },
  mounted() {
  }
});

Vue.component('component4', {
  template: `
    <div>
      {{id}}
    </div>
  `,
  props: ['id'],
});

var app10 = new Vue({
  el: '#app10',
  data: function() {
    return {
      id: '?'
    }
  },
  mounted() {
    bus.$on('idSelected', (value) => {
      console.log('??? app10 click event value: ', value);
      this.id = value;
      console.log('??? this.id', this.id);
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<html>
  <body>
      <div id="app10">
          <component3 :id="id"></component3>
          <component4 :id="id"></component4>
      </div>
  </body>

</html>

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

Tips for maintaining the nested collapsible table row within the main table row in a React MUI table

I am working on implementing a Material UI (MUI) table that includes collapsible table rows. The challenge I am facing is maintaining consistent border and background colors across all the rows, even when some are collapsed. Currently, the separate rows ar ...

Using JavaScript to extract variables from parsed JSON data

Could someone please help me understand how to run this code smoothly without encountering any errors? var test = 'Something'; JSON.parse('{"xxx": test}'); I am inquiring about this because I have a JSON object containing variables th ...

Weekly downloads for NPM show no activity

https://i.stack.imgur.com/4Uhk4.png https://i.stack.imgur.com/0vikS.png Why are all the weekly downloads showing zero for npm packages? I'm new here and confused about why this is happening, any insights? If you could please help me open this issue ...

Issue with useEffect EventListener in REACT HOOKS

Recently, I attempted to create a simple Snake-Game using REACT. Everything was going smoothly until I encountered an issue with using useEffect for moving the "snake" when a keydown event is triggered. The challenge arose when trying to implement moveSnak ...

Dealing with PhantomJS: Tackling the Challenge of XMLHttpRequest Exception 101 Error

As a newcomer to JavaScript and PhantomJS, I have been encountering an issue when running myfile.js (which involves for loops) with the command phantomjs myfile.js. It consistently throws the error: NETWORK_ERR: XMLHttpRequest Exception 101: A network err ...

Is it feasible to refactor the subsequent component without requiring a function to be passed as a prop?

Looking to create a button component that encapsulates loading and error handling for a function passed from its parent. I've outlined an initial approach below, but passing a function as a prop is not recommended in Vue. Reusable Button Component: A ...

What is the best method to update numerous low-resolution image sources with higher resolution images once they have finished loading?

I'm currently developing a website that implements a strategy of loading low-resolution images first, and then swapping them for high-resolution versions once they are fully loaded. By doing this, we aim to speed up the initial loading time by display ...

The link does not respond to the first click

I'm having an issue with the search feature on my website. The page includes an auto-focused text input element. As the user types, an ajax request is made and JQuery fills a div with search results. Each result is represented by an <li> elemen ...

Navigate through each file or image within a directory using Angular

I am facing a challenge with my app where each product has a gallery containing a random number of images, each with a completely unique name. These images are located in /src/assets/images/products/:id/. Currently, I am struggling to loop through and add ...

How do I store the result of an Ajax request as a variable in a different function within a React component?

One of the challenges I'm facing involves making an ajax call that retrieves a list of movies, and then running another function with a separate ajax call to fetch the genre names. Since the first call only provides the genre IDs, I need to match each ...

Having trouble loading data.json file in React.js and jQuery intergration

Having a background in mobile development, I am relatively new to web development so please excuse any amateur questions. Currently, I am working on a react.js project using create-react-app (which utilizes Babel). I am following a tutorial that requires ...

Converting Json arrays to HTML tables using the window.chrome.webview.addEventListener feature with a Server Delphi Application

My Delphi application is sending Json data to the embedded Edge browser, but Javascript is reporting a parser error. https://i.sstatic.net/Z2BUq.png https://i.sstatic.net/0IIzJ.png When I modify the value for Sender.DefaultInterface.PostWebMessageAsJson ...

Exploring the properties of a file directory

As I try to access the d attribute of a path that was generated using Javascript, the output of printing the path element appears as follows: path class=​"coastline" d="M641.2565741281438,207.45837080935186L640.7046722156485,207.0278378856494L640.698 ...

Is it a suboptimal method to repeatedly use order.find, collect data, and transmit a substantial data payload to the front end in

Currently, I am working with Express, React, and MongoDB but I am relatively new to using express and REST API. My goal is to add an analytics feature to my frontend that focuses on sales and orders. The plan is to allow users to search within a specified ...

Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project. Within a specific file named functions.js, I have implemented various functions. Furthermore, in another file named index.js, I have added code to call these functio ...

Assign the value of one variable to another variable using the same keys

I'm facing a scenario where I have two arrays named array1 and array2. My goal is to transfer the values from array2 into array1 for the properties that exist in array1, while keeping the default values for any properties that are not present. One ap ...

"Getting Started with Vue.js: Exploring the setup() and mounted

I recently started using Vue.js and am currently tackling a project. In my setup(), I've declared some constants, with one of them named "c". I found that I can still use console.log(this.c) in mounted() to print out the constant, but when I attempt t ...

Using Firebase with Arrays in Javascript

Currently, my team and I are working on a project using Firebase with Vue.js as the framework. We've come across a challenge regarding creating, updating, and deleting elements in a Firebase cloud document. For instance, within our 'people&apos ...

Using Vue.js to display svg content inside the <svg> element

One of my Vue.js components is responsible for dynamically building the content of an svg element. Let's simplify things and say that the content consists of a <circle cx="50" cy="50" r="60" /> This component achieves this by manipulating a dat ...

Is there a way for me to access the response from the PHP file I'm calling with Ajax?

I am just starting to explore ajax and jquery, and I recently found a code online that I'm tweaking for my own use. However, I am struggling with how to handle responses from PHP in this context. The current setup involves ajax POSTing to a php page ...