Sharing real-time data components in Vue 2.0 with others

Update: I've recently implemented VUEX to efficiently manage and store all my data.


I'm currently facing an issue with data synchronization between components in a container. Although each component's data is stored within the container, it does not update dynamically. Here is an example of the code structure:

Container "father.vue"

import JobDetails from 'components/searchPosition/jobDetails.vue'
export default {
  components: { JobDetails },
  data () {
    return {
      attributes: {
        jobTitle: JobDetails.data().jobTitle,
        ...more data...
      }
    }

Component "son.vue"

export default {
  components: {},
  data () {
    return {
      jobTitle: 'Test',
      ...more data...
    }
  }

When trying to display the jobTitle in the template, it does not reflect changes live as expected:

<pre>
  {{ attributes.jobTitle }} < This value is an input field; changing it doesn't update the container data
</pre>

Is there a method to achieve real-time data synchronization between components?

Answer №1

By not adhering to the Single source of truth principle, you are inadvertently causing harm. This principle is elaborately discussed in Bert Evans' provided link.

While it's possible to have real-time data and updates between components, the approach should be different.

Typically, data should be defined in the parent element and passed down to its children. Any changes within the child component should prompt an update request to the parent. It is recommended not to directly update props. Here's a simple example to illustrate this concept.

Parent

...
data: function() {
   return { text: '' }
},

methods: {
   updateText: function(sText) {
      this.text = sText;
   }
}
...

Child

...
data: function() { return { tmp: '' } },
props: ['text'],
created: function() {
  this.tmp = this.text;
},
methods: {
  emitChange: function() {
    this.$emit('update', this.tmp);
  }
}
...

Template for child

<template>
  <div>
    <input @input="emitChange" v-model="tmp" />
  </div>
</template>

Template of parent

<template>
   <div>
      <child :text="text" @update="updateText" />
   </div>
</template>

In short:

  • The parent holds the actual text data for all components.
  • Child components have an internal 'tmp' value initially set to 'text' from the parent.
  • Changes made to 'tmp' will reflect on the initial text in the parent component.
  • Changes are emitted and the parent listens for these emissions.

Issues with the current example

  • There is no direct connection between 'tmp' and 'text' in the child component as shown in this example. Other child components' changes could potentially overwrite values. Avoid using this exact code if that behavior isn't desired. Nevertheless, the overall concept should now be clearer.

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

Fade in and out on button press

There is a button with the following HTML code: <input type="submit" id="btnApply" name="btnApply" value="Apply"/> Upon clicking the button, a div should be displayed. <div> Thanks for applying </div> The display of the div should fade ...

Tips for handling Vue/Axios JSON payload sent data in Yii2

After spending some time trying to figure it out, I finally realized the solution, which was a bit obvious. I am sharing my answer here so that others can benefit from it and also to see if there is a more efficient way to handle this issue. The problem I ...

Ways to make a jsonp request without including the 'callback' in the URL

I've been working on retrieving information from an Icecast Radio station using their API, which offers the status-json.xsl endpoint to access this data. Despite the format being in xsl, I suspect it returns a JSON file. However, I've encountere ...

What are the steps for utilizing the skrollr library to manipulate text within a div without it being

I'm a beginner in html, css, and javascript and I'm trying to create my first one-page website using the skrollr library. However, I'm facing an issue where the content in my second div is not displaying properly and is hidden behind the fir ...

Customizing the appearance and dimensions of JWPlayer Audio Player with percentage-based styling

I'm currently attempting to set up an audio embed using JWPlayer, following the instructions provided in this particular article. The article suggests setting it up with the following code: <div id="myElement">Loading the player...</div> ...

Retrieve specific JSON information

Below is an example of JSON data: [{ "RM_Name": "Russ Martin", "Division": "East", "RM_Phone": "(603) 491-1259", "RC_Name": "Jacob Sucoff", "RC_Phone": "(800) 247-4154 x3403", "States_Covered": "MT,VT, NH, ME (all firms)", "La ...

Combining React with the power of Express

Currently experimenting with React+Express and encountering an issue related to routing express: router.get('/testCall', function(req, res) { res.json([{id: 'test'}]); }) react: fetch('/testCall') .then((re ...

Excessive content spills off the page (React)

I am new to React and want to create a page that grows and becomes scrollable as the container expands. However, currently the container is overflowing at the top, even though I can scroll to see the bottom part. Check out this link for reference In the ...

Eliminate spaces within a string using JavaScript

In my quest for knowledge about trimming strings in JavaScript, I came across this intriguing discussion with a regex-based solution. After learning from the thread, I was under the assumption that trim would eliminate the space between "Hello" and "World ...

Utilize MaxMind GeoIP2 to identify the city accurately

I have been using this simple code to retrieve the city name through the maxmind service (geoip2). It has been working flawlessly and I am grateful to a fellow member of this site who shared this code with me. However, there is an issue when the user&apos ...

"An issue with ng-controller in AngularJS causing a simple error

Currently, I'm in the process of learning angularJS. While ng-app and ng-model are functioning properly, I've encountered an issue with ng-controller. Despite my efforts, I can't seem to pinpoint where I've gone wrong. My code isn' ...

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...

Regular expressions can be used to remove specific parts of a URL that come before the domain name

Looking for some help with a javascript task involving regex and the split function. Here's what I need to achieve: Input: http://www.google.com/some-page.html Output: http://www.google.com I attempted the following code but unfortunately it didn&ap ...

KineticJS: Applying a filter to an image does not result in the image having a stroke

Working with KineticJS version 5.1.0 I encountered an issue where a KineticJS image that had a stroke lost the stroke after applying a filter to it. I have created a demo showcasing this problem, which can be viewed on JSFiddle. Here is the code snippet: ...

Node Js seems to be taking quite a while to output to the console

Hello, this is my first time posting on Stack Overflow so please bear with me if I make any mistakes. I created a button that, when clicked, decrements the quantity by one. After updating the UI, I send the data to the server. However, when I console log t ...

Selecting DigitalOcean city based on user location in Node.js

Currently, I am implementing Node.js in conjunction with my HTTP server. My goal is to have every user who connects to the server be linked to a real-time game server through WebSockets. Furthermore, I aim for users to automatically connect to the nearest ...

Tips for displaying HTML elements using JSON data in React?

My goal is to dynamically render HTML elements based on JSON data using a React class that takes objects and generates a list of divs. The values inside the divs correspond to the first value in each object within the JSON. Here's an example of the J ...

Techniques for displaying images in JavaScript through iteration

I am currently working on a function where I need to display photos using a loop. In the 'name1' variable, I have the file location of the photos and it changes with each loop iteration. When I use console.log, I can see the file path like "cardI ...

What is the best way to organize large amounts of data into an array?

I am currently working on developing a unique version of wordle using javascript and html. In order to do this, I require a comprehensive list of all possible wordle words stored in an array format. Although I have the words listed within a document contai ...

update certain parts of a webpage using ajax and still allow users to

Currently, I am implementing a partial update feature on the page using Ajax for a shopping cart. The cart updates in real-time as users add items to it. However, there is an issue when users navigate to the checkout page and then click the back button - t ...