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

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

Incorporating a stationary navigation bar alongside a parallax scrolling layout

After spending the entire night trying to figure this out, I have had zero success so far. I decided to tackle this issue with javascript since my attempts with CSS have been completely fruitless. This is a demonstration of the parallax scrolling webpage. ...

Transferring data to a child component through Route parameters

Although I have come across numerous questions and answers related to my query, I still seem unable to implement the solutions correctly. Every time I try, I end up with an 'undefined' error in my props. Let's take a look at my parent compo ...

Showing an Image in Response with Vue.js

After utilizing axios to retrieve an image from the database, I am receiving the res.data in a specific format. My goal is to showcase this image on one of my pages. Here is the code snippet for implementing it: <b-row> <b-col> ...

VueJS waits until the loop is complete before executing a re-render

Check out this VueJS code snippet: new Vue({ el: '#app', data: { tiles: [ { isActive: false }, { isActive: false }, { isActive: false }, { isActive: false }, { isActive: false } ] }, methods: { ...

Incorporate titles for items in the jquery caroufredsel plugin

I am currently using the second example of the caroufredsel plugin, which can be found on this page . I am attempting to add a caption for each picture. To achieve this, I have used `li` and `lis` in my HTML code: <div class="list_carousel"> &l ...

New Solution for Direct Java Raw Printing in Chrome Browser Post NPAPI Discontinuation

It's common knowledge that NPAPI will soon be eliminated from Chrome. Is there a substitute for the Jzebra/QZ Java plugin that allows for raw printing (sending raw ESC/P commands) to POS printers? Are there any Chrome APIs (based on HTML5 and Javasc ...

Guide on incorporating mouse movement while the mouse button is held down in JavaScript

For my project, I want to activate the mouse move event only when the mouse button is held down. I specifically need the action "OK Moved" to be triggered only when both the mouse button is held down and there is mouse movement. This is the code that I h ...

Having trouble getting your Ajax script to function correctly when submitting a form?

I am currently facing an issue where I am loading a partial page, but I do not want the form on this page to redirect when the save button is clicked. I am unsure if I am using the script correctly. I would like to post to the controller when the submit b ...

Table header containing the weekdays for a jQuery calendar display

I need some assistance in creating a basic monthly calendar using a table. Check out this demo: www.jsfiddle.net/pzdw0s2n/1/ ...

Tips for displaying information from two separate MongoDB documents on a single webpage with the help of Mongoose and Express

Currently, I am working with NodeJS, Express, EJS, and Mongoose. While I have a good grasp on most of these technologies, I find myself navigating through the complexities of Mongoose. In my project, I have established two Models that are interconnected w ...

Randomizing filenames for Vue async component chunks

I am currently working on a Laravel app that incorporates numerous Vue components which are being loaded asynchronously using the following method: Vue.component("general-info", function (resolve, reject) { require(["./components/general- ...

Clicking on an element triggers the addition of a class, and the newly

Once the page has finished loading, I am able to utilize jQuery to add a specific class in the following way. $(document).ready(function() { $("#parent").click(function(){ $(".child").addClass("active"); }); }) ...

Troubles with Angular Js: Issues with using $http.put with absolute URLs

Having an issue with $http.put in AngularJS. My server is built with Node.js and my app is in AngularJS. I am trying to make requests from AngularJS to access data on the Node.js server (same host). This code works: $http.put("/fraisforfait", elements); ...

Can you transform your content like Google does?

Looking to create a help page with a layout similar to http://support.google.com/plus/?hl=en. Can anyone provide advice or an example of how to update the new content list without refreshing the page? When you click on something like "circles and streams" ...

Does anyone know of a CSS/JavaScript framework that can be used to replicate the look and functionality of the iOS home

I'm wondering if there is a CSS/JavaScript framework that replicates the layout of an iOS home screen. I want to create a kiosk website with a grid layout similar to Android/iOS where apps can be displayed as icons. ...

The formatting of script sections in .vue files is done by Vetur, excluding the use of Prettier

In a new vue-cli 3.0 project with Typescript and ESlint, I have active plugins in my VSCode including Vetur and Prettier. Despite checking all available settings and trying different approaches, I am struggling to resolve the following issue: Prettier su ...

Ember Gain a comprehensive understanding of the flow of execution between route and controller

Below is a snippet of my "box" route/controller: export default Ember.Controller.extend({ initialized: false, type: 'P', status: 'done', layouts: null, toggleFltr: null, gridVals: Ember.computed.alias('mode ...

Adjust webpage display with JavaScript

Utilizing the mobile-first approach of Zurb Foundation, I successfully created a responsive design. However, my client now requires a direct link labeled "View desktop version" in the footer for when the website is accessed on mobile devices or tablets. T ...

Exploring CryptoJS in a Vue.js project

https://github.com/brix/crypto-js I successfully installed CryptoJS using npm i crypto-js. However, I am facing difficulty in integrating it into my project. When I attempt to use the following code: // Decrypt var bytes = CryptoJS.AES.decrypt(cipher ...