Vue's v-for loop updates all input fields instead of just one, ensuring consistency across the board

After spending hours on this issue, I am still stuck and unable to find a solution through Google search.

The problem lies in my v-for loop where I am iterating over an array of objects. Each iteration renders input fields displaying the name and price of that option. The issue arises when updating one field as all fields get updated simultaneously. Even though they do not share the same v-model, it seems like they do. Below is my HTML code:

            <div
                v-for="(option, index) in options"
                :key="index"
                class="row w-full mt-2"
            >
                <text-input
                    v-model="option.name"
                    label="Option"
                    class="col w-1/2"
                />
                <text-input
                    v-model="option.price"
                    label="Price"
                    prefix="+ €"
                    class="col w-1/4"
                />
            </div>

        <button
            class="text-gray-700 flex items-center mt-3"
            @click.prevent="addNewOption"
        >
            <icon
                icon="icons/plus-circle"
                class="w-4 h-4 mr-2 icon icon-light"
            /> Add options
        </button>

Below is my JavaScript code:

data() {
    return {
       newOption: {
            name: null,
            price: null,
        },

        options: [],
    };
},
methods: {
      addNewOption() {
        this.options.push(this.newOption);
    },
},

If you can identify what I'm doing wrong here, I would greatly appreciate your help.

Thank you in advance!

Answer №1

It appears that by repeatedly adding the same this.newOption object, any changes made to one will affect all instances since they are essentially the same object. Consider using a spread operator or even removing newOptions from the component's state altogether as it does not appear to require reactive state.

data() {
    return {
        options: [],
    };
},
methods: {
    addNewOption() {
        this.options.push({
            name: null,
            price: null,
        });
    },
},

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

Picking a variety of elements and determining their heights using the height

I'm curious why this jQuery code isn't working as expected: hdr = $('.header-wrapper, #top-bar, #new-showroom-header').height(); My intention is to retrieve the heights of multiple elements and store them in a variable. I assumed that ...

Using Node/Express to split the request headers with the .split() method

I am currently working on a way to determine if a specific item exists in the req.headers in order to make a decision on what to send back to the user. Here is my code snippet: function serveAppData(req, res) { console.log("CHECKME", req.headers); //var h ...

Navigating through pages using Jquery's show and hide functionality

How come my item is not returning? I used the .show() method on the item. <div id="back">< back</div> <div class="item">item</div> <div class="content">My content</div> $(function(){ $('.item').on(&apo ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

What is the most effective method for sorting through vast amounts of data with Javascript, React, and Redux?

Currently, I am working with a minimum JSON data set of 90k [...] and utilizing the .filter method. Everything is functioning correctly without any issues, however, from a performance standpoint, I am curious about potential improvements. Any suggestions o ...

Issue with a variable within an *.ejs file

Currently, I am following a guide found at this link, and everything is working smoothly except when I encounter an error on the login screen: ..... 7| >> 8| <% if (message != null) { %> 9| <%= message %> 10| <% } %> 11| message is not defined ...

Developing and integrating views within a node-webkit desktop application

For my file copier desktop application built with node webkit, I aim to create a seamless flow where the initial check for existing profile data determines the first page displayed. The header with static links/buttons to various views remains consistent ...

Broadcast signals to an overarching frame

I have successfully embedded a chatbot (Angular 14 app) in an iframe and now I need to determine whether the frame should be minimized so it can fit within the parent container. My goal is to send custom events to the receiving frame. let iframeCanvas = do ...

Update text displayed on radio button selection using jQuery

Is there a way to change the label text on a selected radio button from "Set default" to just "default" using jQuery? I think I need to use the class radio-default as the selector, but I'm not very familiar with jQuery. <div class="radio-default ...

Error: The function react__WEBPACK_IMPORTED_MODULE_6___default.a.useState is not defined as a function

Hey there! I have been working on some ReactJS code using material-ui, but it seems like I made a mistake with the placement of function handleClickOpen() and function handleClose(). Unfortunately, now my code doesn't compile. Can you help me fix it? ...

Struggling to connect with PouchDB within my HTML-based Web application

I am looking to integrate pouchDB into my WebApp so that upon clicking a button, the data from a JSON file will be saved to pouchDB. In the initial stage in my index.html, I included the following: <script type="module" src="pouchdb/packa ...

How can I add an SVG tooltip that appears when I hover my

I have successfully implemented an SVG map showing marked locations and polygons, with CSS styling that makes the areas stand out on hover. I achieved this without using any JavaScript code. My next goal is to create a hovering window or tooltip that disp ...

Ways to remove the initial row of inline-block divs

My webpage is filled with inline-block divs that are contained within a larger div like so: <div class="container"> <div class="text">Text 1</div> <div class="text">Text 2 ... rest of the nu ...

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

Node/Express API returning empty body when being accessed through fetch or axios requests

Currently working on integrating an API call in a React app using Node/Express. No matter where I place the fetch/axios call, the parsed body always shows up as undefined in my controller. Yesterday, I was experimenting with fetch but decided to switch to ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

Exploring the capabilities of xhr2 using pure javascript

Currently, I am attempting to utilize xhr2 in order to read through a json file. Despite my efforts in researching various methods to accomplish this task, none have proved successful thus far. The function featured below my require statements is the one t ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...

retrieve information instantly on AngularJS by utilizing $http or $resource

I designed a plugin for field customization. angular.module('ersProfileForm').directive('ersProfileEditableField', ['$templateCache', '$compile', 'profileFieldService', 'RolesService', ...

Choosing a single random key-value pair from a specific attribute within a JSON schema

Is there a way to generate a new JSON schema based on the existing one, but with only one key-value pair chosen randomly from the "properties" attribute? The new schema should retain the "title" and "type" attributes as well. { "title": "animals object" ...