Create a unique V-MODEL for each index that I generate

How can I customize the V-MODEL for each object generated?

I am developing a cupcake website where users can create multiple forms with just one submission.

However, when generating two fields, the inputs of the second field are linked to the inputs of the first field.

Here's the code snippet I'm working on:

<template>
  <div>
    <button @click="cupcakes.push(def)">Add Cupcake</button>

    <div v-for="(cupcake, index) in cupcakes" :key="index">
      <input type="text" v-model="cupcakes[index].name">
      <input type="text" v-model="cupcakes[index].description">
      <input type="text" v-model="cupcakes[index].type">
      <input type="text" v-model="cupcakes[index].prize">
      <input type="text" v-model="cupcakes[index].color">
    </div>

    <button @click="onSubmit">Create Cupcake</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cupcakes: [],
      def: {
        name: '',
        description: 'Originals',
        type: 'small',
        prize: 500,
        color: 'color'
      }
    }
  },

  methods: {
    onSubmit() {
      console.log(this.cupcakes);
    }
  }
}
</script>

I have attempted different methods, but none seem to work as expected.

How can I detach the two fields so that upon submission, it only captures the user input in each respective field?

Answer №1

When adding an object multiple times to your cupcakes Array, you're essentially pushing the same reference (def) each time. This means that updating cupcakes[n] will only update the values of the original object.

To avoid this, it's better to send a copy of the object into the cupcakes array:

<button @click="cupcakes.push(JSON.parse(JSON.stringify(def)))">Add Cup Cake</button>

A more effective approach would be creating a method that generates a new cupcake:

<template>
  <div>
    <button @click="cupcakes.push(getNewCupcake())">Add Cup Cake</button>

    <div v-for="(cupcake, index) in cupcakes" :key="index">
      <input type="text" v-model="cupcakes[index].name">
      <input type="text" v-model="cupcakes[index].description">
      <input type="text" v-model="cupcakes[index].type">
      <input type="text" v-model="cupcakes[index].prize">
      <input type="text" v-model="cupcakes[index].color">
    </div>

    <button @click="onSubmit">Create Cupcate</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cupcakes: []
    };
  },
  methods: {
    onSubmit() {
      console.log(this.cupcakes);
    },
    getNewCupcake() {
      return {
        name: "",
        description: "Originals",
        type: "small",
        prize: 500,
        color: "color"
      }
    }
  }
};
</script>

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

Why does the width of my image appear differently on an iPhone compared to other devices?

I recently encountered an issue with the responsiveness of an image on my website. While it displayed correctly on Android and desktop devices, the image appeared distorted on iPhones as if the CSS width attribute was not applied properly. This problem spe ...

What is the process for making changes to a document in Mongoose?

My goal is to allow users to update existing mongoose documents using a form with method-override package. Despite trying various solutions found on Stackoverflow, I have not been able to resolve my issue. The desired functionality is for the user to view ...

Splitting JavaScript Arrays: Exploring Efficient Division

I'm attempting to develop a recursive function that divides an array in half until it only consists of lengths of 3 and 2. After dividing, I want to neatly organize all the new arrays into another array. My idea is to find a way to determine the numb ...

AJAX-powered Form Validation

I am in the process of creating a login form that includes three input fields: one for entering a username, another for entering a password, and a submit button to log in. Currently, I am utilizing AJAX to validate the login information directly on the cl ...

The equivalent of ESM for resolving modules using the `createRequire` function with a specified

In the process of developing a JavaScript instrumentation engine, I am currently focused on traversing a source file's Abstract Syntax Tree (AST) and queuing imported modules for instrumentation in a recursive manner. In order to achieve this, it is c ...

Achieving dynamic page number display in relation to Pagination in ReactJS

I have a website that was created by someone else, and the pagination feature is becoming overwhelming for me as I am not a coder or developer. Image Link Currently, my navigation pagination displays 17 pages. I would like to limit this to only showing 1 ...

Issues with the History API in AJAX Requests

Recently, I have come across a dynamically generated PHP code: <script> parent.document.title = 'Members | UrbanRanks'; $("#cwrocket_button").click(function(){ $("#module").load("modu ...

What is the method for adding an HTML tag that includes an md-checkbox and md-icon?

I am currently utilizing angular material and angular js to dynamically add a new HTML div when a certain function is triggered from the view. Here is my view setup: <div id = "main_row" ng-click="defCtrl.submit()"> </div> This is wh ...

Incorporating CSS into React.js applications

I am currently working on a project using MERN.io. In my project, I am utilizing the React.js component Dropdown. However, the Dropdown component does not come with its own style and CSS, resulting in no styling at all. ... import Dropdown from 'rea ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

Using TypeScript, implement a function that is called when a React checkbox's state changes to true

Currently, I am experimenting with the react feature called onChange. My goal is to update local data by adding a value when a checkbox is selected. Conversely, when the checkbox is unselected, I just want to display the original data. However, I find that ...

What are some ways I can troubleshoot my contact form?

As someone new to web design, I recently completed my very first site using a combination of HTML, CSS, and a touch of JavaScript. I managed to create a small contact form within the site, but now I'm wondering if there's a way to make it functio ...

Customize Vue components for easy drag and drop functionality

I am attempting to implement custom draggable components using the vuedraggable package, but I am facing issues in making it work. Additionally, I want the functionality to copy the component instead of moving it altogether. Below is the code snippet: < ...

What is the best method for choosing the parent elements?

I am attempting to create a sidebar that saves the last clicked link in local storage and still displays the collapsed links after the page is reloaded. $(".clickedLink").parent().parent().css('background-color', 'green'); Ca ...

Using Selenium with JavaScript and Python to simulate key presses

Is there a way to simulate key presses as if typing on a keyboard? I am looking to programmatically click on an input element and then emulate the user typing by pressing keys. I prefer not to use XPath selectors combined with sendkeys or similar methods. ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Automatically compute and convert currency formats using JavaScript

May I ask again? Hopefully you understand. I am looking to automatically calculate with a money format. Here is a demo: https://jsfiddle.net/xp4ky2gg/ This is my code... HTML code <table style="width:100%"> ...

The visualization rendered by ChartJS is not displaying correctly when data is fetched using an AJAX call

When it comes to creating visualizations from static datasets using ChartJS, I have no problems. However, the issue arises when I try to use data fetched via an AJAX call - the visualization does not render properly. Surprisingly, no errors are thrown even ...

The Vue.js transition feature seems to be malfunctioning when trying to display a modal

I can't figure out why my animation isn't working with Vue transitions. Here is the code I have: <template> <teleport to="body"> <div class="modal-overlay" v-if="loading"> <transitio ...

Utilize SVGs efficiently by loading them once and reusing them

Is it possible to use the same SVG element twice on a web page without having to load it again? I am changing the CSS of the SVG using JavaScript, so I believe the SVG must be directly embedded in the HTML rather than included as an object. Both instance ...