Is it possible to transfer data between two child components in Vue.js that share a common parent component?

In my project, I am working with 2 components that have a shared parent. My goal is to pass data from one child component to the other effectively. (I am specifically using vueJS 2 for this task)

Answer №1

For effective communication, the parent component should manage it in the following manner:

  1. The first child sends the data to the parent component.
this.$emit('myVarChanged', this.myVar);
  1. The parent component listens for the emitted data, saves the new value, and then passes it to the second child like so:
<ChildOneComponent @myVarChanged="updateMyVar" />
data() { return { myVar:null } }
methods: {
     updateMyVar(val){
          this.myVar = val;
     }
}
<ChildTwoComponent :myVar="myVar" />
  1. The second child receives the updated value as a prop:
props: ['myVar']

Demonstration:

const child1 = Vue.component('child1', {
  template: '#child1',
  data() { return { count:0 } },
  methods: {
    updateParent() { this.$emit('myvarchanged', this.count++); }
  }
});

const child2 = Vue.component('child2', {
  template: '#child2',
  props: ['myvar']
});

new Vue({
  el:"#app",
  components: { child1, child2 },
  data() { return { myvar:null } },
  methods: {
    updateMyVar(val) { this.myvar = val; }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template id="child1">
  <div>
    <h1>Child 1</h1>
    <button @click="updateParent">Click to send to child 2</button>
  </div>
</template>

<template id="child2">
  <div>
    <h1>Child 2</h1>
    <p>Prop from child 1: {{myvar}}</p>
  </div>
</template>

<div id="app">
  <div><child1 @myvarchanged="updateMyVar" /></div>
  <div><child2 :myvar="myvar" /></div>
</div>

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

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

Having an issue with Jquery selector where the text does not match

HTML Code <select id="myDropdown"> <option selected="selected" value="0">default</option> <option value="1">bananas</option> <option value="2">pears</option> </select> Javascript Function setDr ...

Transfer information from a single form and distribute it across multiple forms with the help of jQuery or Javascript

Form1 has a variety of input fields including text, select, radio, and textarea. At the bottom there is a button labeled "copy" that allows users to copy data from all the fields in Form1. In different pages, I have three to four other forms with input fi ...

Steps for Integrating a Web Service Reference in NodeJS

Can a Web reference be added to a NodeJS project similar to how it's done in .NET framework Web API Projects? Essentially, the NodeJS API project will serve as a middleware between the Front End and an XML Web service. The XML Web service is a secure ...

Enhancing State in React Component through Prop Update

I am aiming to achieve the functionality of clicking a button in a child component and having that component removed. I am new to React and currently in my app.js file, I have a component with a prop like this: <IntroSteps isHidden={false} /> Inside ...

How can I properly redirect an HTTP request to HTTPS on my Express server?

Currently, I am working on my API and have configured it to work with the HTTPS protocol using SSL. Here is the code snippet: https.createServer({ key: fs.readFileSync(certKeySSLPath), cert: fs.readFileSync(certSSLPath) }, app).listen(serverPORTHTT ...

What criteria does Vue use to determine which select option should be pre-selected when the app is initialized?

I recently came across this app on jsFiddle: https://jsfiddle.net/punter/ggatev5k/1/ , also shared here: <div id="app"> <select v-model="teamsSelected"> <option v-for="team in teams" :value="{id: team.id, name: team.name}">{{team.na ...

Access the session on both routers

I currently have 2 different routers set up in my application: Router 1 app.post('/consultations', function(req, res) { req.session.name = 'administrator'; console.log('test', req.session.name); // the session is pro ...

What is the method to adjust the anchor point for a MUI popover?

I currently have the following code for handling a popover: const [open, setOpen] = useState(false); const anchorRef = createRef() const handleClose = () => { setOpen(false); }; const handleClick = useCallback( (event: MouseEvent<H ...

Troubleshooting: Issues with Jquery's replaceWith function

I'm facing an issue with a table I have that includes a button in one of its columns. The button is supposed to toggle the class of the current row in the table and then replace itself once clicked. $(document).ready(function() { $(".checkOut"). ...

Spinner loading animation not showing correctly

Even though it shows up when I hover over and inspect, the image remains completely invisible. It's saved in the same folder and I believe all the file names are correct, but for some reason, it's just not working as expected. Any help would be g ...

Reconfigure the Node application using Express to seamlessly access modules through route files

I recently created a basic app using npm express. After generating the app.js file, I attempted to add new modules but encountered an issue where I couldn't access them in the route files. For example, when trying to utilize the 'request' mo ...

Tips for retaining a chosen selection in a dropdown box using AngularJS

How can I store the selected color value from a dropdown box into the $scope.color variable? Index.html: <label class="item item-select" name="selectName"> <span class="input-label">Choose your favorite color:</span> <select id="colo ...

Vuejs has the capability for dynamic image binding which allows for images to be dynamically loaded and displayed based on

I'm having trouble figuring out how to dynamically bind an image in Vuejs from an external site. Here's the code that is currently working: <v-btn v-for="item in items" :key="item.id" :to="item.path" color="white" class=" ...

Is there a way to retrieve the contents of a vue component (such as a modal window) when clicking a button that is located within a different vue component?

I'm in the process of organizing my basic Vue application into components. I have a product listing where each item has some information and a button. When the user clicks on the button (referred to as the "more details" button), a modal window opens ...

What is the best way to only load a specific div from another webpage onto my own webpage without loading the entire page?

I am currently working with two webpages named internal.html and external.html Within internal.html, I have the following code snippet that loads external.html into a div with the id "result": <script src="http://ajax.googleapis.com/ajax/libs/jquer ...

Updating the innerHTML of a frameset

I have a unique challenge that involves loading the frameset of www.example.com/2.html when accessing www.example.com/en/test/page.html. Successfully accomplished this task. Now, after loading 2.html in the frameset, I want to modify ".html" to ".html" t ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...

Adding an element to the second-to-last position in a list

In the context of a HTML unordered list <ul id = "master_key_list"> <li id="master_key_23" class="available_element">Fix the Peanut Butter</li> <li id="master_key_24" class="available_element">Focus on Price Sensitivity</li& ...

JavaScrip $("").text(); is a straightforward way to recognize and extract

At the moment, I am utilizing the jQuery script below: $("TD.info > font").text(); when this specific HTML structure is present on a webpage: <td class="info"> <font> 3001474535 </font> </td> I had the idea to tweak t ...