Vue - component props not properly updating when object changes are made

Within the main structure, I have both obj and newObj objects. I am monitoring any changes that occur within the obj object using deep: true, and then updating newObj accordingly.

Although in my vue debugger, it appears that newObj has been updated as expected, the component does not seem to execute the for loop count. Additionally, when attempting to display {{ newObj }}, only the initial update is logged.

I attempted to replicate the issue on this corresponding Fiddle: here.

Here is my HTML setup:

<div id="app">
  <button @click="appendTo">Append</button>
  <my-comp v-bind:new-obj="newObj"></my-comp>
</div>

And here is the Vue configuration:

new Vue({
  el: '#app',
  data: {
    obj: {},
    newObj: {}
  },

  methods: {
    appendTo() {
      if (typeof this.obj[1] === 'undefined') {
        this.$set(this.obj, 1, {})
      }

      var randLetter = String.fromCharCode(Math.floor(Math.random() * (122 - 97)) + 97);
         this.$set(this.obj[1], randLetter, [ [] ])
      }
    },

  watch: {
    obj: {
        handler(obj) {
        var oldKeys = Object.keys(obj)
        var newKeys = Object.keys(this.newObj);

        var removedIndex = newKeys.filter(x => oldKeys.indexOf(x) < 0 );
        for (var i = 0, len = removedIndex.length; i < len; i++) {
          delete this.newObj[removedIndex[i]]
        }

        oldKeys.map((key) => {
          if (this.newObj.hasOwnProperty(key)) {
            var newInnerKeys = Object.keys(this.newObj[key]);
            var oldInnerKeys = Object.keys(obj[key]);

            var additions = oldInnerKeys.filter(x => newInnerKeys.indexOf(x) < 0);

            for (var i = 0, len = additions.length; i < len; i++) {
              // here
              this.$set(this.newObj[key], additions[i], [ [] ]);
            }

            var deletions = newInnerKeys.filter(x => oldInnerKeys.indexOf(x) < 0);
            for (var i = 0, len = deletions.length; i < len; i++) {
              delete this.newObj[key][deletions[i]]
            }

          } else {
            this.newObj[key] = {}
            for (var innerKey in obj[key]) {
              this.$set(this.newObj, key, {
                [innerKey]: [ [] ]
              });
            }
          }

          console.log(obj);
          console.log(this.newObj)
        });
      },
      deep: true
    }
  }
})

Vue.component('my-comp', {
    props: ['newObj'],
  template: `
        <div>
        <div v-for="item in newObj">
            test
      </div>
    </div>
  `
})

Answer №1

Your data newObj utilizes a getter and setter that are established by Vue. Whenever the setter is invoked, it triggers a UI re-render. It's important to note that the setter gets triggered when you modify the reference of newObj, but not when you change its value. For example:

this.newObj = {} // will trigger the setter

this.newObj['key'] = 'value' // does not trigger the setter

If you want to monitor changes deeply on the property this.newObj, you can add a deep watcher. Alternatively, you can alter its reference using a workaround:

this.newObj = Object.assign({}, this.newObject);

This method effectively creates a copy of the object newObject.

Feel free to check out the updated fiddle here.

https://jsfiddle.net/749nc5d2/

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

The method .makePerspective() in THREE.Matrix4 has been updated with a new signature. Make sure to refer to the documentation for more information

Attempting to run a functional three.js code using release 119 of three.js (instead of r79) has resulted in an error being thrown by the previously functioning code: THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check ...

Changing a single variable into an array that holds the variable in JavaScript

Is there a way to change 5 into [5] using JavaScript? I need this functionality for a method that utilizes jQuery's $.inArray. It should be able to handle both scalar variables and arrays, converting scalars into arrays with a single element. ...

Connecting to a pathway of Material-UI menu items

I am currently utilizing Material-UI's menu components as part of my project requirements. However, I am encountering difficulties in properly routing each MenuItem to an existing route within my application. As a temporary solution, I have resorted ...

Merge two separate mongodb records

Just getting started with javascript / express / mongodb. For my initial project, I am working on a simple task manager where todos are categorized by priority - "high," "mid," or "low." However, I am facing an issue when trying to display different entri ...

What is preventing me from utilizing middleware in my express route?

I have a project in progress where I am developing an API. As part of this process, I need to implement a user system and ensure secure access to the API. Below is the middleware function used for validation: 'use strict' const jwt = require(& ...

I'm curious about the purpose of the "^=" operator in this algorithm for finding the unpaired numbers. What exactly does it do?

I came across a fascinating code snippet that helps find a unique number in a list of duplicate numbers (where each number appears twice, except for one). function findNonPaired(listOfNumbers) { let nonPairedNumber = 0 listOfNumbers.forEach((n) => ...

Tips for utilizing a single mongoose default connection across various files in MongoDB?

I'm struggling to figure out how to share a mongoose connection across multiple files. Here's an example: User.js var mongoose = require("../DataAccess/DbConnection"); var userSchema = new Schema({ email: {type: String, required: true,max ...

Capture a snapshot with Protractor using the Jasmine2 Screenshot Reporter

The Protractor configuration file includes 2 custom reporting options: one for logging and the other is the protractor-jasmine2-screenshot-reporter. However, only a blank white screen is displayed when generating a screenshot png. Below is the code snippet ...

error": "message": "Property 'name' cannot be read because it is undefined

I've encountered an issue while creating a route to handle POST data. Despite testing it on postman, I have not been able to find a solution for the problem that many others seem to be facing as well. It seems like the 'name' field is not be ...

Mesh object circling in the opposite direction of the displayed image

Working on replicating a Flash website using Three.JS and facing difficulty in achieving desired functionality. The goal is to create button images that orbit around the center of the screen, stop when hovered over by the mouse, and open a different locat ...

Incorporate a vibrant red circle within a tab of the navigation bar

I'm looking to incorporate a red dot with a number into a messaging tab to indicate new messages. Below is the HTML code: <ul class="nav pw-nav pw-nav--horizontal"> <li class="nav-item"> <a class="nav ...

What is the best way to incorporate external HTML content while ensuring HTML5 compatibility? Exploring the different approaches of using PHP, HTML

While this may seem like a simple task to the experts out there, I have been struggling for over an hour without success... My objective is to use a single footer file and menu file for all my webpages while considering blocking, speed, and other factors. ...

The jQuery functions are unable to function properly when retrieving AJAX data

I am currently working on a script that inserts a record into my database using AJAX. After inserting the data, it is posted back in the following format... Print "<li>"; Print "<span class='cost'>" . $bill. "</span> "; Print ...

Is it possible to change the style of an element when I hover over one of its children?

Encountered an issue while working with HTML and CSS: //HTML <div> <div class="sibling-hover">hover over me</div> </div> <div class="parent"> <div>should disappear</div> </div> ...

An issue has occurred while trying to execute the npm start command within PhpStorm

When I try to run npm start on Windows' command prompt, it works fine. However, I encounter errors when running it in the PhpStorm Terminal. You can see the errors here. Is this a result of them being different platforms or could it be related to som ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Combining Three.js with iFrame for a mix of WebGL and CSS3D

After some experimentation, I successfully created a dynamic page that seamlessly integrates WebGL and CSS3D (with valuable guidance from this helpful SO post). To add an extra touch, I included an iframe: However, I noticed that the functionality to inte ...

What causes the URL to be undefined after making a JQuery Ajax POST request?

After performing an Ajax Post within a Profile View, I am attempting to refresh the view. Here is the code snippet: $.ajax({ url: '/Profile/Index', dataType: "html", type: "POST", data: JSON.stringify(10), success: ...

Changing the default yarn registry for a specific project

Typically, I fetch packages from the internal server by using the command: yarn config set registry http://custom-packages-server.com However, for a new project, I want to switch back to the default registry without affecting other projects. If I try cha ...

New to Angular: Struggling with complex form validation?

I am just starting to explore Angular and I want to tackle some more advanced input validation. My task involves a table where each row has three text inputs. I need to validate that at least one row has three non-empty input fields. If this criteria is m ...