The process of deep copying a Javascript object is not functioning properly within the Vue.js framework

When passing a clone of an object from a parent component to a child component using props, I encounter an issue where changing the value of the status property in the parent component's object also updates the value in the "cloned" object within the child component.

Despite knowing that Object.assign() method performs shallow copying, my object properties are primitive type String and should be copied by value not reference. I have tried various methods like manual assignment and JSON parsing but none of them work as expected.

In the Parent Component: AppServers

<template>
  <div>
    <AppServerStatus v-for="server in servers"   :serverObj="JSON.parse(JSON.stringify(server))">
    </AppServerStatus>
    <hr>
    <button @click="changeStatus()">Change server 2</button>
  </div>
</template>

...

In the Child Component: AppServerStatus

<template>
  <div>
    <h3>Server Name: {{ serverObj.name }}</h3>
    <p>Server Status: {{ serverObj.status }}</p>
    <hr>
  </div>
</template>

...

The expectation is for the value of status property in the child component's object to remain as Normal even after executing changeStatus() in the parent component, however, it too gets updated.

Answer №1

To prevent unintended reactivity, it is recommended to create a new object using the information from the serverObj prop during the created or mounted lifecycle hook.

<template>
  <div>
    <h3>Server Name: {{ server.name }}</h3>
    <p>Server Status: {{ server.status }}</p>
    <hr>
  </div>
</template>

<script>
  export default {
    name: 'AppServerStatus',
    data() {
      return {
        status: 'Critical',
        server: {
          name: '',
          status: ''
        }
      }
    },

    props: [
      'serverObj'
    ],

    mounted() {
       this.server = {
         name: this.serverObj.name,
         status: this.serverObj.status
       };
    }
  }
</script>

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 CSS file is failing to recognize the changes made to the data-theme attribute in the HTML

Currently implementing a dark theme on my website involves adding a toggle switch to the footer.html page, which adds a variable named data-theme = 'dark' to the html. The scss files of the footer and core are adjusting accordingly based on the c ...

Assigning data to a dropdown in AngularJS using two separate controllers

Currently working with angularJS, I am exploring ways to bind the value of a select element within the scope of controller A and use it as an argument for an ng-click call (specifically the getQuizByCampID() Function) in the scope of controller B. Initial ...

Enhancing the efficiency of JavaScript code

Imagine you have a web application processing 1,000,000 user logins per hour. and the code below is executed during each user login: if (DevMode) { // make an Ajax call } else if (RealMode) { // make another Ajax call } else { // Do something ...

Tips on handling a redirection request following a fetch post request

When communicating with my node server (Express) using fetch to build a Single Page Application (SPA), I have encountered an issue. Upon each request to the server, I validate the session and redirect to a login page if it is not valid. However, I noticed ...

Is it possible to activate or deactivate a button depending on a radio button selection using jQuery?

Below is the code I have written in an aspx file: <asp:Button ID="btn" runat="server" Text="Add As a Sub Organization" OnClick="lnkChild_Click" ValidationGroup="GroupA" class="btn-u" CausesValidation="true" /> <asp:GridView ID="grdDuplicateO ...

Creating a Utils class in Vue.js with seamless access to Vuex through this.$store

I have a situation where I need to retrieve state from the Vuex store using this.$store. After some research, I discovered that creating a custom plugin with an installed instance method might be the solution. Here is my plugin implementation: index.ts i ...

Efficiently verifying elements within an array

I have a roster of students categorized based on their activity status - some are active, while others are inactive. var allActive = [{id: 1, active: true}, {id: 2, active: true}, , {id: 3, active: true}]; var someNot = [{id: 4, active: true}, {id: 5, act ...

Is it possible to alter the parent scope from an AngularJS directive?

I am currently in the process of constructing my initial Angular application, but I am encountering some difficulties while attempting to achieve a specific functionality. The issue revolves around a video container which is supposed to remain hidden until ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Tips for displaying a message box in ASP.NET

In my C# website development project, I am faced with the challenge of displaying a message box using JavaScript. I have successfully implemented it using the following code: Response.Write("<script LANGUAGE='JavaScript' >alert('Login ...

Swapping out an entire chunk of information in a JSON document

Currently, I am seeking a solution to update specific data in a JSON file without altering any other sections within it: { "task": [ { "id": 5, "title": "dave", "description": "test" }, { "id": 6, "title": "fdds ...

Send the cookie with the JSON request

While logged into a secure website with a login, I came across some valuable data that is transmitted through the server in JSON format. By opening Chrome and inspecting the page using the "Network" tab, I discovered a URL utilizing XHR which contained the ...

What is the best way to eliminate all padding from a bootstrap toast notification?

I'm attempting to display a bootstrap alert message as an overlay toast (so it automatically disappears and appears above other elements). Issue: I am encountering a gap at the bottom of the toast and struggling to remove it: https://jsfiddle.net/der ...

Having trouble setting a value for a textbox in angularjs

Greetings! I am currently working on a web application using AngularJS. My task involves binding data from various API's to a textbox in my project. Below is the snippet of the HTML code where I attempt to achieve this: <input class="with-icon" ty ...

Going through items in a container

Is it possible to pass X number of components into a slot and iterate through them in Vue? Here's an example... <Foo> <template #abc> <Bar /> <Bar /> <Bar /> </template> <template #def>Baz</tem ...

What is the best way to display an overlay internal link on top of the current one after it has been clicked

I am looking to create a button that, when clicked, will slide in a different page link and modify the URL to cover 80% of the website, while keeping the previous page in the background. Upon closing, the URL will revert back to the original one. I have c ...

How can we prevent dispatching within a dispatch in React Flux?

It seems that I have come across a situation where I am struggling to avoid the dispatch-within-a-dispatch problem in Flux. While I have found similar questions addressing this issue, none of the solutions provided seem to be ideal, as they often involve ...

What is the method for showcasing a single Observable from an Array of Observables in Angular?

I am facing a challenge with displaying questions from an Observable-Array one by one. Currently, I can only display all the questions at once using *ngFor in my HTML. Here is my component code snippet: import { Component, OnInit } from '@angula ...

Using PHP to pass variables to an external JavaScript file

I have come across the following code snippet: PHP <?php include("db.php"); ?> <html> <head> <title>Title</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/j ...

Execute the function numerous times that is associated with an asynchronous function in JavaScript

I am currently working on two functions: one is asynchronous as it fetches data from a CSV file, and the other function renders a list of cities. The CSV file contains information about shops located in various cities. My goal is to display a list of cit ...