tips for setting up initial state using props in Vue 3 without altering the props

When setting up the state in my Vue 3 component, I use the following approach:

data() {
    return {
        new_listing: this.listing //which is a prop
    }
}

But when I link it to an input field like this:

<input type="text" placeholder="title" v-model="new_listing.title" />

I expect only new_listing.title to change, but it appears that the prop listing is also being affected. How can I ensure that only the state new_listing.title changes without impacting the prop listing.title.

Answer №1

One essential step is to duplicate the object (create a new copy).

In the realm of JavaScript, when you assign an object to a variable, it doesn't generate a fresh copy of that object. Instead, it simply points back to the original object.

So, in your specific coding scenario, using { new_listing: this.listing } results in linking the this.listing object to new_listing. Consequently, any alterations made to new_listing will also impact this.listing:

To replicate the object in ES6+, consider the following approach. The ... symbolizes a spread syntax. It acts as a method for cloning an object.

data() {
    return {
        new_listing: {...this.listing} //which represents a prop
    }
}

If you're not utilizing ES6, explore What is the most efficient way to deep clone an object in JavaScript? for insights on how to create a copy of an object.

Note: In cases where the object comprises objects (e.g. {a: {b: "h"}}), embarking on a deep clone becomes necessary (cloning objects within other objects).

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

When using Javascript template literals, they function properly when assigned to a variable, but they do not work when included in a JSON

Trying to get a grasp of Javascript. Let's say I have a variable declared with template literals: var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.` This functions correctly as sh ...

Creating a dynamic route in Node Express allows for flexible path handling

Is there a way to incorporate a dynamic route or path using the Express package? The challenge is that the path is an ID passed by the client and we have no control over it. const express = require('express'); const dynamicPath = express(); dyn ...

"Connection Failure: MongoDB Server Unreachable"`

I've been working on a basic web application using MongoDB, Express, and NodeJS. Unfortunately, I've encountered an issue where I cannot connect to MongoDB and keep receiving the following error message in the terminal: (node:28265) UnhandledPro ...

Creating a dynamic TextField that updates on change using React JS

Hey there, I recently embarked on my React learning journey and encountered an issue while trying to dynamically pass data from a response to my TextField. It appears that the TextField is not editable as the onChange function does not seem to be working. ...

What is the accurate user agent for Windows Phone?

Can someone explain why PHP and JavaScript produce different user agents? Which one is considered the accurate user agent? PHP User Agent Output: <?php print_r($_SERVER['HTTP_USER_AGENT']); ?> User Agent: Mozilla/5.0 (Mobile; Windows Ph ...

Custom CSS Being Overridden by Bootstrap Styles

In my Vue-2 project, I utilize Vue-Router, Webpack, and Bootstrap-Vue. Bootstrap is loaded globally at the root of my application as it is utilized across the entire app. The views in my app are categorized into internal and external routes, with sub-route ...

Trouble arises when attempting to establish an isolated scope within Angular alongside UI Bootstrap

My table of data is set up with AngularJS, and one of the columns is calculated using a function in the controller. On my webpage, I have a button that opens a modal. When I use UI Bootstrap to open the modal, it creates a new isolated scope (child of the ...

Organize Image Collection in an Asp.Net MVC Webpage

Looking to build an Asp.Net MVC 5 (Razor) view and controller that can manage a collection of images. Consider a model similar to the following (where the data is stored in a database and accessed using EF): public class Game { public Guid Id {get; se ...

Are web components capable of managing changes in CSS (maybe through cssChangedCallback)?

Is there a way to control the application of CSS to a web component similar to using attributes through attributeChangedCallback. I am currently developing a couple of web components that could benefit from being styled with CSS classes. However, I requir ...

Issue arises when attempting to submit multiple form fields with identical 'name' attributes, preventing the fields from being posted

Currently, I am facing a challenge with old HTML/JavaScript code. Some parts I have control over, while others are generated from an external source that I cannot manage. There is a form created dynamically with hidden fields. The form is produced using a ...

What causes the 'this' to be undefined in React event handlers?

It is common knowledge that in the React code provided, this will be undefined. Various approaches such as binding and arrow functions can solve this issue. What I am interested in is understanding the rationale behind this behavior. Kindly elucidate on ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

Discover the white circle search bar display

I am attempting to implement a circular reveal animation to display the search toolbar in my web application using CSS and JavaScript. My goal is to achieve a similar effect as seen on Whatsapp for Android. https://i.sstatic.net/YE242.jpg I have successfu ...

transforming JSON into CSV structure

I am attempting to utilize a JSON file as input data. Below is an excerpt of sample data. [ { id: 1671349531, name: "A Wild Restaurant Expansion", blurb: "We are looking to expand from our current location to a new and better facility...", goal: 17000, pl ...

How to Retrieve URL Before Closing a jQuery Window Using window.open()?

Is it feasible to retrieve the URL of a window.open window after triggering a window.close event when the user clicks the close button? How can I obtain the last URL visited right before the window closes? ...

Leverage the power of Symfony and Vue by seamlessly incorporating _variables.scss into every Vue component with the help of

I need help integrating my _variables.sccs file into all Vue components in a Symfony + Vue.js project. I want to access the scss variables within the style blocks of each component. While I know how to achieve this in a vue-cli created app using vue.confi ...

Is it significant if a function within a React component is impure?

Is it acceptable to directly reference a prop in a helper function created to streamline the internal logic of a react component, or is it considered a code smell? Should the prop be passed in as an extra argument to create a pure function instead? Here&a ...

Scriptmanager and Rokbox clash in a heated confrontation

I'm having trouble getting RokBox to display images on my webpage because the asp:ScriptManager seems to be causing some issues. After trying to troubleshoot, I found that when I remove the following code: <asp:ScriptManager ID="ScriptManager1" r ...

Transfer the data from external event hosting platforms to LinkedIn and Facebook for seamless integration

I am currently working on a web application that allows users to create events based on their needs. I want to synchronize the event details with LinkedIn and Facebook events. I am utilizing Java servlets and jQuery/JavaScript for the front end. Are ther ...

Instead of adding a new object to the array, consider increasing the quantity of an existing object

I am new to working with a shopping cart component and my code is structured like this: let cartCount = document.getElementById("counter"); let isItemSelected = false; let itemCount = 0; let shoppingCart = []; let selectedSize = ""; let displaySelectedSiz ...