Generating forms dynamically in Vue using code

I'm looking to prompt the user to specify how many points they want to create, followed by entering coordinates for each point.

One approach I attempted involved using an initial text field to capture the number of points desired, and then using a loop to generate a form for each point. While this method successfully creates the forms, I am struggling to retrieve the values entered in each form.

Is there a more effective way to achieve this? How can I properly capture and store the values from each form?


<template>
  <div>
    <v-card class="mb-3">
      <v-card-text>
        <v-text-field label="How many nodes" :value="nodes" @input="onInput" type="number"></v-text-field>
      </v-card-text>
    </v-card>
    <v-container fluid grid-list-md>
      <v-layout row wrap>
        <template v-for="i in nodes">
          <v-flex :key="i" xs12 md3>
            <div>
              <v-card class="mb-3">
                <v-card-text>
                  <div>Node {{i}}</div>
                  <v-text-field label="Coord X" value="x1" @input="getValues" type="number" v-model="no1"></v-text-field>
                  <v-text-field label="Coord Y" :value="y1" @input="getValues" type="number"></v-text-field>
                </v-card-text>
              </v-card>
            </div>
          </v-flex>
        </template>
      </v-layout>
    </v-container>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        nodes: 2
      }
    },
    methods: {
      onInput (val) {
        this.nodes = parseInt(val)
      }
    }
  }
</script>

Answer №1

In my opinion, a more effective approach would be to implement it like this:

   <template>
      <div>
        <v-card class="mb-3">
          <v-card-text>
            <v-text-field label="How many nodes" v-model="nodes" type="number"></v-text-field>
          </v-card-text>
        </v-card>
        <v-container fluid grid-list-md>
          <v-layout row wrap>
            <template v-for="(node, index) in nodesArr">
              <v-flex :key="i" xs12 md3>
                <div>
                  <v-card class="mb-3">
                    <v-card-text>
                      <div>Node {{index + 1}}</div>
                      <v-text-field label="Coord X" v-model="node[index].coordX" type="number" v-model="no1"></v-text-field>
                      <v-text-field label="Coord Y" v-model="node[index].coordY" type="number"></v-text-field>
                    </v-card-text>
                  </v-card>
                </div>
              </v-flex>
            </template>
          </v-layout>
        </v-container>
      </div>
    </template>
    <script>
      export default {
        data () {
          return {
            nodes: 0,
            nodesArr: []
          }
        },
        watch: {
            nodes(newVal) {
                this.nodesArr = [];
                for(var i=0; i<this.nodes; i++){
                    this.nodesArr.push({coordX: "", coordY: ""});
                }
            }
        },
        methods: {
        }
      }
    </script>

Explanation of the code:

  1. Add a

    v-model< /a> on the input field to capture the number of nodes entered and bind it to the <code>nodes
    property.

  2. Create a new property named nodesArr : [] to iterate through and display each set of coordinates

  3. Implement a watcher on the nodes property that populates the nodesArr array with objects containing empty coordX and coordY values based on the number of nodes provided

  4. Utilize

    v-for="(node, index) in nodesArr"
    to loop through nodesArr and display the input fields for x-coordinate and y-coordinate

  5. Bind the x-coordinate input to the respective coordX property using the index obtained from v-for
  6. Similarly, bind the y-coordinate input to the corresponding coordY property using the index provided by v-for
  7. With two-way binding via v-model, all input data is stored in the nodesArr property for future use

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

How to use AngularJS to showcase intricate data structures

Here is the JSON data that I have: { "_id": "543e95d78a1cec2a38ed53ec", "result": { "CAR009": [ { "name": "BMW" }, { "name": "MERCEDES" } ], "BUS007": [ { ...

Utilize Jquery to interact with Android's date picker interface

Currently, I am developing an application for IOS and Android using Phonegap with Cordova 2.2.0. In my development process, I am utilizing jQuery and HTML5 technologies. While working on the IOS version, I found that simply setting the input type to "dat ...

Customize the width of a DataTable cell in VuetifyJS

I am currently utilizing the VuetifyJS Data Table and I'm looking for a way to reduce the spacing between the entries in each header cell. Adding a width to each header did not achieve the desired result, as it seems there is a minimum predefined widt ...

Creating expandable card components with React and CSS using accordion functionality

I am currently working on creating a card that will expand its blue footer when the "view details" link is clicked to show lorem text. However, I am encountering an issue where the blue bottom of the card does not expand along with the lorem text. You can ...

Is it possible to incorporate conditionals within a jade template using JavaScript?

I've been working on a Jade template that includes some logic, but I seem to be encountering an issue. Here's the code snippet: #container -for(var col=0; col < 2 ;col++){ - if(col % 4 == 0){ .movie_row - } ...

Integration of a QR code scanner on a WordPress website page

I'm in the process of setting up a QR code scanner on my Wordpress site or within a popup. The goal is for users to be able to scan a QR code when they visit the page/popup link. Specifically, the QR code will represent a WooCommerce product URL, and ...

A significant decrease in speed is noticeable when Raphael JS is utilized with a large number of rectangles with backgrounds

I am faced with a challenge involving a large collection of small rectangles (4K-5K) and I am looking to implement the sprite technique in order to assign them a background using just one image to avoid overwhelming the server with requests. When I opt fo ...

What is Mozilla's reasoning for deeming Conditional catch-blocks as non-conventional?

I recently came across a document on Mozilla that described the try...catch conditional as "non-standard and is not on a standards track. Do not use it in production" However, I am curious to understand the reason behind this statement. I also want t ...

I have an inquiry regarding the live method

$('.classname').live('click',function() { some code; }); Would there be any performance issues if there are around 100 to 300 elements with this specific class? ...

I'm a beginner in jest and I'm curious, how should I go about writing a test for this

Below is a method I have called onViewed: onViewed() { const { current } = this.state; this.slides[current] = { ...this.slides[current], viewed: true }; const filtered = _.filter(this.slides, slide => slide.section === this.slides[current].s ...

Guide to setting up Bootstrap dismissable alert using webpack

While setting up Bootstrap using webpack, I am individually loading JS files: import '../../../scss/app/app.scss'; import 'popper.js'; import 'bootstrap/js/dist/tooltip'; import 'bootstrap/js/dist/popover'; import & ...

What is the best way to save a POST request response to a database using NodeJs?

Currently, I am using the Post method with axios.js and node.js successfully. The request is being made, but unfortunately, the data is not being saved to the database. This is the section of my code where I implement the request using axios.js: teste ...

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

Using jQuery's .html() method to update the inner HTML of an element can cause the .click() event on a form button to stop functioning

There is a puzzling issue with my HTML form button and jQuery functionality. The button is supposed to trigger a .click() event from a JavaScript file, and it was working perfectly until I used jQuery .html() to replace the main page content with the form ...

If you don't get the correct response from the $.ajax success function

I am utilizing the $.ajax function to retrieve content, however I am encountering an issue when attempting to display special tags from it. The data appears to be missing! This is how I am currently handling it: $(document).ready(function(){ $("button") ...

How to create a boolean observable that emits hot values with switchMap?

Looking to develop a method named isEmpty:Observable<boolean> that generates a hot Observable<boolean> by employing a switchMap. Here's what I have so far: /** * Notifies observers when the store is empty. */ protected notifyOnE ...

AngularJS SmartyUI position not dynamically updating on SmartyStreets plugin

In my angularJS application, I am utilizing SmartyStreets' LiveAddress for address validation and autofilling two fields in a form. After the user submits the form, a message (either success or failure) is displayed in a div above the form. However, t ...

Unable to scroll on the initial page of mobile phone as the scroll bar is missing; refreshing the page resolves the issue

I recently added a small JS code to my original website to implement a new feature. Everything seemed to be working fine, but I noticed that when the page is first loaded, there is no scroll bar. However, if I refresh the page, the scroll bar appears. I tr ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...