Sending information to a child component causes the parent's data to be modified as well

Transferring information from the parent to the child component has always been easy for me. However, I recently encountered an issue where updating the data in the child component also updates the data in the parent component simultaneously. Now, I am looking for a way to prevent this from happening.

Within the parent component, there is a child component embedded like this:

    <address-dialog v-if="dialog.address.status" :countries="countries" :address-data="dialog.address.data" 
:open="dialog.address.status" @close="dialog.address.status = !dialog.address.status"></address-dialog>

In the child component, I pass the props as they are and then initialize them using the data method.

props: {
    open: {
        type: Boolean,
        default: false
    },
    addressData: {
        type: Object,
        default: null
    },
    countries: {
        type: Array,
        default: null
    }
},

data() {
    return {
        mdiClose,
        loading: false,
        valid: false,
        dialog: this.open,
        address: this.addressData,
        cities: [],
        states: [],
        overlay: false,
        snackbar: {
            status: false, 
            text: '',
            color: '#FF5252'
        },
        rules: {
            required: value => !!value || 'Required.',
        },
    }
},

Whenever I update the address in the child component, it automatically updates the address in the parent component. How can I prevent this automatic updating?

Answer №1

The reason is that they share the same reference, since the address is considered an object.

An effective way to resolve this issue is by passing a new object containing the addressData properties using the spread operator.

address: { ...this.addressData }

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

What is the method for retrieving the XMLHttpRequest errors registered with addEventListener?

I am struggling to find a solution. https://i.stack.imgur.com/bRJho.gif ...

The system is unable to locate the module at 'C:UsersSanjaiAppDataRoaming pm ode_modulesprotractorinprotractor'. This error originates from internal/modules/cjs/loader.js at line 960

After running "protractor conf.js" without any issues, I decided to install protractor globally using the command "npm install -g protractor". However, after installing protractor globally, I encountered the following error message: internal/modules/cjs/lo ...

Incorporating jquery-ui Datepicker with dynamic text input functionality

In my table list, I have multiple input fields with the jQuery datepicker implemented. Each input field is assigned the class "datepicker" and a unique ID number. When clicked on, the datepicker pops up allowing for date selection to be inserted into the f ...

What is the best way to import JSON functionality into Javascript specifically for use with Internet Explorer

I am facing an issue with loading JSON feature in JavaScript for IE8 while in compatibility mode. After receiving advice, I decided to utilize douglascrockford/JSON-js to enable JSON support on outdated browsers. To tackle this problem, I created a new f ...

Form duplicates messages sent

I have made some adjustments to a free form, and it seems to be functioning properly. However, I have encountered an issue where the email is being sent twice and the message is written twice after completion. I attempted to replace the button and input ...

What is the best way to locate the closest points using their positions?

I have a cluster of orbs arranged in the following pattern: https://i.sstatic.net/9FhsQ.png Each orb is evenly spaced from one another. The code I am using for this setup is: geometry = new THREE.SphereGeometry(1.2); material = new THREE.MeshPhongMateri ...

How can you temporarily stop an event with a click or touch, and then resume the event's state after performing certain tasks in jQuery?

Exploring options for tracking clicks with precision - interested in finding a way to defer the event propagation until a certain function completes. Any suggestions on an alternative approach or how to effectively delay the normal event flow? $(this).on ...

After upgrading, my npm is completely dysfunctional – it keeps showing the error "Cannot read property 'get' of undefined."

Recently, I updated Node.js to the latest version on my computer. Prior to the update, the 'npm' command functioned flawlessly in the command prompt. However, after installing the new version of Node.js, it stopped working completely. All comma ...

JavaScript code to read a .txt file

Is it possible to use JavaScript to read a text file directly with the file path provided in the code, rather than selecting the file from an open file window? ...

Exploring the different pages in React js

I am currently working on implementing a button in React Js that, when clicked, should navigate to another screen. However, I keep encountering an error: TypeError: Cannot read property 'push' of undefined. I have tried various solutions but noth ...

validate the existence of the username upon submission of the form

Here is some code that I have written. .js $(document).ready(function() { $("#username").focusout(function() { $.ajax({ type:'post', url:site_url()+'/client/checkUserName', data:{&apos ...

Display icons within each table cell row

Objective: I want to implement a feature where icons appear when the cursor is inside a td row, allowing users to click on them. These icons will contain links. When the cursor moves to a new td row, the previous row should return to its default state a ...

Issue with Vue 3: Button components fail to update upon modification of second dropdown menu

As a newcomer to Vue, I've encountered a challenging issue that I'm struggling to solve. Despite making significant progress on a complex project, I find myself perplexed by what should be a simple feature... A Brief Background/Overview: The pro ...

Exploring ways to dynamically alter templates using the link function in Angular.js

Recently, I developed a directive called widget which functions similar to ng-view, but the template name is derived from an attribute. app.directive('widget', function() { return { restrict: 'EA', scope: true, ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

Need help triggering Ajax code upon clicking a link?

Can someone help me find the issue with my script? Below is the code snippet: <script> $(".icross").click(function(e){ e.preventDefault(); var obj = $(this); $.ajax({ type: "GET", url: "supprimer.php", data: 'id=&a ...

Mobile devices experiencing issues in loading Javascript scripts

Let me start by sharing my JS code: function getTimeRemaining(endTimeInput) { var endTime = new Date(endTimeInput); var currentTime = new Date(); var t = endTime - currentTime; var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 100 ...

Error Encountered: Unable to utilize $(...).mask function with jQuery in ASP.NET using C#

I have encountered an issue while working on a task involving jQuery masked for date. When running the task in HTML, it works perfectly fine. However, when attempting to run it in ASP.NET, I face the problem where 'mask is not a function'. Below ...

Is there a way to dynamically insert page breaks in jspdf to ensure that tables do not split across multiple pages?

I am currently working on developing a website that can generate PDFs from database information, using PHP and MySQL to create tables with variable lengths. Sometimes, these tables may even span across multiple pages. If the first table takes up too much ...

Steps to create a conditional AJAX request triggered by the onbeforeload event depending on the value of a variable

My website script tracks user login status in real time using "onbeforeunload", ajax, and logout.php. This method updates the MySQL database with a value of 1 or 0 to indicate if a user is logged in. Unlike monitoring cookies, this approach allows accurate ...