Vue's push() method is replacing existing data in the array

I'm currently facing an issue where I am transferring data from a child component, Form, to its parent component, App. The data transfer is functioning correctly, however, when attempting to add this data to the existing array within the App component, all previous elements within the array are being overwritten. As a result, the same element ends up appearing in each position.

<template>
  <Form :addPC="getPC" />
</template>

<script>
import Form from './components/Form.vue'
export default {
  name: 'App',
  components:{
    Form,
  },
  methods:{
    getPC(pc)
    {
      var PC = {}
      PC = pc
      this.PCs.push(PC)
      console.log(this.PCs)
    }
  },
  data(){
      return{
        PCs:[]
      }
    },
}
</script>

Answer №1

It seems like you are encountering a common issue where saving the same object reference in your "pcs" array causes changes to be reflected in all elements. One way to resolve this is by creating a new object using the spread operator before pushing it into the array.

getPC(pc) {
    // Create a new object using the spread operator
    const newPC = { ...pc };
    this.PCs.push(newPC);
    console.log(this.PCs);
  }

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

React higher order component (HOC) DOM attributes are causing the error message 'Unknown event handler property' to be triggered

I recently created a Higher Order Component (HOC) using recompose, but I'm encountering a React Warning every time the props are passed down. Warning: Unknown event handler property `onSaveChanges`. It will be ignored. All my properties with a speci ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

Mastering the use of the edit feature in Vue.js

Trying to modify a todo list by implementing a feature that displays a text input field when the edit button is toggled. However, currently, clicking the button causes the input box to appear for all todos in the list. Here's the modified code: < ...

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...

Leveraging a JavaScript variable declared outside the function to successfully transfer data to my AJAX function

Every time the enter key is pressed, my AJAX function gets executed. I used to pass a set of javascript variables equal to elements in the HTML (the contents of a text area) as data for the AJAX function. Now, I want these JS variables to hold values from ...

In NextJS, where is the best place to run sensitive code to ensure it is only executed server-side?

I'm currently exploring the world of NextJS and I am in the process of figuring out how to structure my project with a solid architecture that prioritizes security. However, I find myself at a crossroads when it comes to determining the best place to ...

Check for pattern using JavaScript regular expression

Utilizing ng-pattern to validate a regular expression. The pattern must include 3 letters and 2 numbers in a group. For example: G-31SSD or G-EEE43 Currently, the pattern only matches the second example. ng-model="newGroup.groupCode" ng-pattern="/^&bso ...

What are the signs that indicate a potential code breakage following an upgrade of the JavaScript library in use?

Imagine you have incorporated multiple JavaScript libraries into your website. Your code interacts with various APIs, but occasionally, after an update, one of the APIs changes and causes your code to break without any prior notice. What steps can you tak ...

Converting Numbers into Words with the power of HTML and JavaScript

CONVERT NUMBER TO WORDS Write a simple JavaScript program that converts a number to words. Include an HTML page where the user can input the number to be converted. The conversion process should involve using both for loops and switch statements. ...

Customizing upload directories in elfinder for dynamic path generation

In my CodeIgniter project, I am trying to configure elfinder to have a dynamic upload path for each unique ID. The folder structure I am working with is as follows: Below are my elfinder settings: $idce = $_GET['id_c']; $client_code = $this- ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Discovering the method for accessing nested JSON data through ng-repeat in AngularJS

I'm attempting to access the items._id value within ng-view using ng-repeat. I am able to retrieve all data, but I am interested in specific data only. Data.json [ { _id : "td6v9db4514cc4ewew4334", firstName : 'ayaz', la ...

Setting up React Native on a Mac M1 device

I am currently setting up React Native on my MacBook M1 Despite having installed npm, JDK, Node, Rosetta, CocoaPod, VSCode, Android Studio, Xcode and more, when I try to run the command (npm start), the directories for iOS and Android are not present. The ...

Populate a pair of div elements using just one AJAX request

Currently, I am attempting to use the load() function to ajaxly load two separate divs, #follow-x and #follow-y, by clicking a button. The approach I have taken is as follows within the success function of my code snippet. However, this method does not see ...

Tips for Holding Off on Assigning Variables in Vue3 Component Until Pinia Store Data is Ready

I am currently developing a Vue.js application with Pinia for state management. In my component, I need to assign variables based on data retrieved from a Pinia store. However, I am facing an issue where the component assigns variables before the store dat ...

``tips for concealing the sidebar on a Vue.js application`

Welcome everyone, I am a newcomer to Vue and have decided to use a CoreUI admin panel to work on some cool Vue projects. However, I have hit a roadblock while working on the nav.js file. export default { items: [ { ...

What is the process for obtaining a compilation of warnings from the next.js terminal?

While running my project on VScode, I noticed a series of warnings appearing in the terminal. One specific warning that caught my attention is: The `bg-variant` mixin has been deprecated as of v4.4.0. It will be removed entirely in v5. on line 8 ...

Pixijs is unable to load spritesheets correctly

I am currently facing an issue while trying to load a spritesheet in PixiJS following the instructions provided on Below is the code snippet I am using: PIXI.Loader.shared.add('sheet', require('../assets/spritesheet.json')).load(sprite ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...