Child component not properly receiving updated Vue props data

Hey everyone, I'm seeking clarity on Vue props data. I've been passing values from a parent component to a child component. The issue I'm facing is that when the data in the parent component changes or updates, it doesn't reflect in the child component.

Vue.component('child-component', {
  template: '<div class="child">{{val}}</div>',
  props: ['testData'],
  data: function () {
    return {
        val: this.testData
    }
  }
});

However, if I use the props name {{testdata}}, it correctly displays the data from the parent.

Vue.component('child-component', {
  template: '<div class="child">{{testData}}</div>',
  props: ['testData'],
  data: function () {
    return {
        val: this.testData
    }
  }
});

Thank you in advance for your help!

Fiddle link

Answer №1

Let me illustrate this concept with a straightforward example

let x = 'hello'
let y = x
x = 'world'

console.log('x:', x)
console.log('y:', y)

When you set...

val: this.sampleData

You are defining the initial value of val when the component is first created. Any changes to the prop will not affect val, similar to how modifications in x do not impact y.

For more information, visit https://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow

Answer №2

I am determined to solve this! this.$set(this.mesas, i, event);

data() {
    return { mesas: [] }
},
components: {
    'table-item': table_l,    
},
methods: {
    deleteMesa: function(event) {
        let i = this.mesas.map(item => item.id).indexOf(event.id);
        console.log("deleting table", i); 
        this.mesas.splice(i, 1);
    },
    updateMesa: function(event) {
        let i =this.mesas.map(item => item.id).indexOf(event.id);
        console.log("updating table", i); 
        ///    Using this method Vue shows a warning
        //this.mesas[i]=event;  
        /// Here is how I solved it
        this.$set(this.mesas, i, event);
     },
     // Adds new tables
     addMesa: function(newTable) {
         console.log(newTable);
         this.mesas.push(newTable);
     }
}

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

One typical approach in React/JavaScript for monitoring the runtime of every function within a program

Experimenting with different techniques such as performance.now() or new Date().getTime() has been done in order to monitor the processing time of every function/method. However, specifying these methods within each function for time calculation purposes h ...

There is a lag in the loading of css stylesheets

We created a single-page company website that utilizes three different stylesheets connected to the index.html. By clicking a button, users can switch between these stylesheets resulting in changes to colors, images, and text colors. However, Issue 1: The ...

The $.ajax request encounters an error when trying to parse the data as JSON

I am encountering an issue where my ajax call to a JSON file fails when using dataType: "json". However, changing it to "text" allows the ajax call to succeed. See the code snippet below: $.ajax({ type: "POST", url: url, dataType: "json", ...

Determine the text's length inside a div element by utilizing the div itself

I have a div with a fixed width of 30% and I am trying to find the length of the text within that div. Check out my JSFiddle for the code. The current code snippet I am using is: var text=$('#test').text(); text=text.trim(); var len=text.lengt ...

Steps to trigger a JavaScript popup from an iframe window to the parent window

Currently I am developing a web application using JSP with JavaScript. Within the parent window, an iframe is being utilized. The issue arises when a button in the iframe page is clicked, as it opens a popup window within the iframe itself. However, my obj ...

Angular is having trouble with the toggle menu button in the Bootstrap template

I recently integrated this template into my Angular project, which you can view at [. I copied the entire template code into my home.component.html file; everything seems to be working fine as the CSS is loading correctly and the layout matches the origina ...

Limiting a text based on spaces or at the completion of a word within a string or sentence

Currently, I am utilizing a LimitTo filter to generate excerpts of article descriptions for display on the homepage of a website as snippets in the feature section. The LimitTo filter is set at a maximum of "100 characters," but it sometimes cuts off word ...

What is the best way to implement Bootstrap's range input design with noUiSlider?

Is it possible to customize the appearance of the noUiSlider to resemble the Bootstrap style for input ranges? This would involve changing the handle shape to a circle and modifying the sliding range. You can see an example below showcasing both the noUiSl ...

Attempting to configure Kafka consumer and producer components

Trying to establish a basic producer-consumer flow with Kafka, utilizing node-rdkafka Operating in debug: 'all' mode, the logs display: Producer: test [0]: MessageSet with 1 message(s) delivered Consumer: Fetch topic test [0] at offset 38 (v2) ...

What is the method for specifying a null value in Typescript?

I'm curious if this code snippet is accurate, or if there's a better way to define it. Is there an alternative to using error!? I'm unsure of its meaning and would appreciate clarification. ...

Prevent duplicate key errors when performing bulk insert operations with MongoDB

Is there a way to perform a bulk insert and proceed even if a duplicate key error occurs? I have a collection with a unique index on the id field (not _id) and some existing data. I need to add new data to the collection while skipping any documents that ...

Effortlessly upload multiple dynamic files using Nest JS

Attempting to upload files with dynamic keys, however nest.js requires key names. Attempted solution: @UseInterceptors(FilesInterceptor('files')) async uploadFile(@Query() minioDto: MinioDto, @UploadedFiles() files: Array<BufferedFi ...

Enhancing Pinia setup stores with custom getters, setters, and actions for improved reusability

If we think about a Pinia setup store that has a basic set of state, getters, and actions in place: export const useBaseStore = defineStore('base-store', () => { const name = ref<string>(''); const age = ref<number>(1 ...

Dealing with unexpected behavior in NodeJS multi-class file by listening for uncaught exceptions using the `process.on('uncaughtException

I have isolated my code to a minimal, complete, and verifiable example (MCVE). I originally anticipated that it would trigger the process.on('uncaughtException') event, but instead it is being caught by the process.on('unhandledRejection&apo ...

Issues with Internet Explorer's scaling functionality are preventing it from operating correctly

I've utilized d3 to create a map. Its width is dynamically set based on the parent div's (with the id "map") width, and its height is calculated with a ratio of 5/9 in relation to the width. The viewBox attribute has been defined as "0 0 width he ...

Guide on incorporating Admin LTE 3 into Nuxt.js

Is there a way to seamlessly combine adminlte 3 with Nuxt.js? Following the installation of adminlte 3 via npm, I attempted to add css and js files in nuxt.config.js. While the styles appear to be functioning correctly, the javascript is not executing as ...

Looking to add a gradient color to the header in React JS?

Looking for some assistance with my project! I have a simple project that requires gradient colors in the header background. Check it out here and please help me with adding the gradient colors :) import { LinearGradient } from 'expo-linear-gradient& ...

Ensure that the dynamically inserted <title> tag remains intact in Angular even when the page is re

Can the dynamic title tag be preserved when the page is refreshed? When I refresh the page, the title tag reverts back to the original one specified in the index.html temporarily before switching back to the dynamically added one. I want the title tag to ...

Obtain the templateUrl using the ui-router functionality

Perhaps the title is a bit unclear. I am currently working on two Angular apps nested within each other. Each has its own router created using `ui-router`. If I call a state that is not recognized by the main router, I would like it to search for this sta ...

Using npm link with Webpack results in eslint errors

I have a multi-package project setup, where I have one JavaScript package that depends on a TypeScript library. Initially, I was using Sinopia and had to reinstall the TypeScript library every time I made changes to it. Then I discovered npm link and thoug ...