Modifying the value of a property in one model will also result in the modification of the same

As a beginner with Vue, I am looking to allow users to add specific social media links to the page and customize properties like text. There are two objects in my data - models and defaults.

The defaults object contains selectable options for social media links and their initial values. Essentially, I copy the default value into models and enable users to personalize the model through inputs.

 data () {
      return  {

            models : [] ,
            defaults : {

                twitter : { id : null , placeholder : 'my twitter' , icon : 'twitter'  , text : null  , 'link' : null } ,
                instagram   : { id : null , placeholder : 'my instagram'  , icon : 'instagram' , text : null  , 'link' : null } ,
                tiktok   : { id : null , placeholder : 'my tiktok'  , icon : 'tiktok' , text : null  , 'link' : null } ,

            } ,
      }
    } ,     

There is a select menu for users to choose which social media platform they want to add to the page.

Select : 
<ul >
  <li v-for="(social, index ) in defaults" :key="index"> 
     <a @click="appendSocial(index)">
       {{ index }}
     </a> 
  </li>
</ul>

This is my

@click="appendSocial(index)"
function:

appendSocial(type){
    let typedefault = this.defaults[type];
    this.models.push(typedefault)
},

Finally, I display the models to the user and provide an input for editing its text using v-model.

<div v-for="(model, index) in models" v-bind:key="model.id">

    <a class="button-preview">
        {{ model.text === null ? model.placeholder : model.text }}
    </a>
   
    <label>Text</label>
    <input type="text"   v-model="model.text"  :key="index" :placeholder="model.placeholder">

</div>

The issue arises when changing properties in models or defaults changes the corresponding properties in the other object unexpectedly. For example, modifying the text of a Twitter link in models will also update the text in defaults.twitter.text.

To illustrate the problem, console logs have been added to the appendSocial function:

    appendSocial(type){
        let typedefault = this.defaults[type];
        console.log(`-------- default object for ${type} -----------`);
        console.log(typedefault);
        this.addElement(typedefault);
    },

Here are the results:

https://i.sstatic.net/U5gXN.png

1 - A Twitter link was selected and added to models, showing that defaults.twitter.text is null

2 - The text in model.text (assumed to be models[0].text) was changed to "abc"

3 - Another Twitter link was added, resulting in defaults.twitter.text also becoming "abc"

Moreover, modifying properties in defaults affects all models that initially received their values from that default object. For instance, changing defaults.instagram.text to "xyz" alters the text in all models derived from defaults.instagram to "xyz".

It seems like there is a reference between them, even though no value was passed by reference between the two objects. I am unsure of what is causing this behavior and how to prevent it?

Answer №1

This is because

    let typedefault = this.defaults[type];
    this.models.push(typedefault)

The reference to the object is being stored in the this.models array. Therefore, if you make changes to the element, it will automatically modify the base object. If you need to create a deep clone, a quick and simple method is as follows:

let typedefault = this.defaults[type];
let clonedObj = JSON.parse(JSON.stringify(typedefault));
this.models.push(clonedObj)

Please note that the Lodash library provides a proper deep clone functionality. https://www.geeksforgeeks.org/lodash-_-clonedeep-method/

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

Sending URL parameters from a React frontend to an Express API call involves crafting the request URL with

I'm currently working on a project where I need to make a fetch request from React to Express. The API URL requires parameters, but I want the last part of the URL to be dynamic. How can I pass a parameter from React to the Express API URL? Here' ...

Ways to stop Bootstrap 4 dropdown from appearing when clicking on an input field?

Here is a straightforward bootstrap dropdown menu example, but with a twist - the toggle element is a text input. Instead of showing the dropdown on click event, I want it to appear when the user inputs something so I can dynamically populate the menu base ...

Exploring the Shopware 6 Admin API: Saving a new entity with a default entity property

How can I set a default value for a new entity property (such as defaultCurrency.id) within the sw-entity-single-select component before calling this.repository.save()? Is this possible, or do I have to wait until after calling save() and then listen for ...

Can anyone suggest a method to block the execution of Javascript commands in the console?

Regarding the inquiry mentioned in the question title. Is it possible to prevent individuals from executing functions on my webpage using the console, even though it is not necessary? I have experimented with various methods, and the code below represent ...

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

Discovering the method to extract a specific section from a lengthy string

Looking to extract phone numbers from an HTML source code using PHP? Each phone number in the code starts with 'phone=' and ends with %. For example, consider the following sample HTML code: b2e1d163b0b4dc6ebfa5&amp;t=s&amp;phone=9535503 ...

Requirements for using Angular JS and Node JS

With upcoming projects involving AngularJS and Node.js, I'm a bit apprehensive as I don't have much experience with JavaScript. Should I start by picking up a book on each technology, or is it essential to learn more about JavaScript first before ...

Exploring the Past: How the History API, Ajax Pages, and

I have a layout for my website that looks like this IMAGE I am experimenting with creating page transitions using ajax and the history API. CODE: history.pushState(null, null, "/members/" + dataLink + ".php" ); // update URL console. ...

Swap out original source files in HTML with minified versions

I have successfully utilized a maven plugin to create a minified and compressed version of my CSS and JavaScript files. Now, I am looking to update the section in my main HTML page that currently loads all those individual files. Here is what it looks lik ...

Unable to receive comment reply through Ajax without refreshing the comment section

I'm facing an issue where I cannot retrieve comment replies via Ajax under comments, even though the replies are successfully saved in the database. Oddly enough, upon refreshing the Index.php page, the replies display correctly. I suspect the problem ...

I am interested in utilizing $axios in conjunction with Vuex constants for my project

My Dream Becoming Reality I frequently use this.$axios, so I attempted to store it in a constant, but unfortunately, it did not work as expected. Despite reading the official documentation, I couldn't grasp the reason behind this issue. Could it be d ...

Incorporate Y-axis titles onto D3 bar chart using the attribute 'name' from JSON data

While following the tutorial on creating a bar chart, I encountered an issue in step three. The bars are rotated to columns, but I am struggling to iterate over a JSON dataset and add Y-axis labels for each bar using the name attribute from the returned JS ...

Having an issue with the Show/Hide Javascript toggle on the same page. Multiple hidden texts are appearing simultaneously. Seeking a solution without the use of JQuery

This code is functioning efficiently. I am looking for a way to display and conceal various texts using different expand/hide links within multiple tables on the same page. I prefer to achieve this without using JQuery, just like in this straightforward sc ...

What is the best way to activate a click event in Vue.js?

Hey there! I'm facing a situation where I have a button within the child component that emits an event when clicked. Is there a way to trigger this event when the parent component is mounted? Alternatively, is there another method to achieve this goal ...

Unable to create a new user account

I have been working on developing an e-commerce platform using the MERN stack, but I have encountered an issue with registering new users. The system only allows me to register the first user successfully after clearing the database, but subsequent registr ...

Using Three.js to apply multiple images onto a sphere and have individual control over each one

I have a 3D sphere that I am looking to map an array of images onto. I want to be able to control each image independently, allowing for fading in and out of each image. To better illustrate my goal, I will provide an example image of what I am trying to a ...

Incorrect order in Angular2 NgFor within tree model when elements are removed and then added back

Currently experimenting with Angular 2 alpha version 44. Working with a tree model that utilizes recursion for display purposes. Each group contains 'Criterions', 'Segments', and other 'Groups'. Elements can be added or delet ...

Refresh stock value in anychart without having to re-render the entire chart

I am currently experimenting with the Anychart stock candlestick chart and I must say, it is quite impressive. However, I have encountered an issue while trying to update the chart using a setInterval function. The problem is that it re-plots the entire ch ...

An unusual phenomenon in the controller hierarchy causing issues with accessing the parent scope in AngularJS

Recently delving into the world of angularjs, I encountered something perplexing that seemed like a glitch in the controller hierarchy when it comes to accessing the parent scope. Here are two code snippets that I believed should both function properly bas ...

What is the most efficient way to organize an array by date?

Here is the data I have: const data = [{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44}, {date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53}, {date: "2022-05 ...