Vue.JS enables the seamless addition of rows to a form on the fly

I am currently working on creating a dynamic form using Vue. The concept is that when the user clicks the add button, another row will appear for them to input data. However, I encountered an issue where initially only 1 row was set up, but when I added the v-for attribute to the div, 3 extra rows started appearing. I'm puzzled as to why this occurred and also noticed that nothing happens when I click the add button. Any insights would be greatly appreciated. Thank you.

View the dynamic vue form image https://i.stack.imgur.com/VNLtR.jpg

Component

<div class="container">
<title>exportDATA | Web to Excel</title>
<div class="mt-4">
        <div class="jumbotron bg-dark col-md-10 offset-md-1">
                <div class="card card-body bg-dark" v-for="(user,index) in users" :key="index">
                   <form>
                        <div class="row">
                            <div class="form-group col-md-3">
                                <label for="email" class="text-white">Username:</label>
                                <input type="text" class="form-control" id="username" v-model="user.username">
                            </div>
                            <div class="form-group col-md-3">
                                <label for="pwd" class="text-white">Password:</label>
                                <input type="password" class="form-control" id="password" v-model="user.password">
                            </div>
                            <div class="form-group col-md-3">
                                <label for="pwd" class="text-white">Phone Number:</label>
                                <input type="text" class="form-control" id="phone" v-model="user.phone">
                            </div>
                            <div class="form-group col-md-3">
                                <label for="pwd" class="text-white">Email</label>
                                <input type="email" class="form-control" id="email" v-model="user.email">
                            </div>
                        </div>
                    </form>
                </div>            
             <br>
                <button class="btn btn-secondary float-right" title="Click to add row"><span class="fa fa-plus-square" @click="addMoreData(index)" v-show="index == users.length-1"></span> &nbsp;Add More Data</button>
        </div>

        <div class="jumbotron bg-dark col-md-10 offset-md-1 ">
            <button class="btn btn-success col-md-6 offset-md-3 p-3"><span class="fa fa-plus-square"></span> &nbsp;Export to Microsoft Excel</button>
        </div>            
</div>
</div>

Script

    export default {
    data(){
      return{   
          users:{
              username:'',
              password:'',
              email:'',
              phone:''
          }
      }
    },
    methods:{
        addMoreData(index){
            this.users.push({ 
                username: '',
                password:'',
                email:'',
                phone:''
                });
        }

    },
    mounted() {
        console.log('Component mounted.')
    }
}

Answer №1

Ensure that your data is structured as an array with objects. In this case, the v-for directive is used to loop through properties within a single object.

data(){
      return{   
          users: [{
              username:'',
              password:'',
              email:'',
              phone:''
          }]
      }
    },

Answer №2

Utilize vue-autoextra to streamline the process of adding items to a collection without the need for an additional button:

Vue.config.devtools = false
Vue.config.productionTip = false
const app = new Vue({
  el: '#app',
  data () {
    return {
      users: [
        { name: 'Alice', password: 'xyz' },
      ]
    }
  },
  components: {
    Autoextra
  }
})
@import "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css";
.last {
  opacity: .5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8cecddd95d9cdccd7ddc0cccad9f888968a9688">[email protected]</a>/dist/vue-autoextra.min.js"></script>

    <div class="container" id="app">
      <div class="columns">
        <div class="column">
          <autoextra :collection="users" v-slot="{item,last,index}">
            <div class="columns is-mobile" :class="{last: last}">
              <div class="field column">
                <div class="control">
                  <label class="label">{{last ? 'New ' : ''}}User {{!last ? index + 1 : ''}}</label>
                  <input class="input" type="text" v-model="item.name"/>
                </div>
              </div>
              <div class="field column">
                <label class="label">Password</label>
                <div class="control">
                  <input class="input" type="password" v-model="item.password"/>
                </div>
              </div>            
            </div>
          </autoextra> 
        </div>
        <div class="column">
          <pre>{{users}}</pre>
        </div>

      </div>
    </div>

Answer №3

<button class="btn btn-secondary float-right" title="Click to add row">
<span class="fa fa-plus-square" @click="addMoreData(index)" v-show="index == users.length-1"></span> &nbsp;Add More Data
</button>

Why is the

@click="addMoreData(index)"
function call placed inside the <span> element? This placement doesn't seem logical and it will not work as expected! Can the variables index and users be accessed in this context?

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

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

What is the best way to streamline JSON file data by selectively extracting necessary information?

After exporting my user data from Firebase, I am looking to streamline the JSON file by filtering only the necessary fields for my data model. The format of the file obtained from Firebase is as follows: { "Users": { "00uniqueuserid3& ...

Challenges arise when attempting to authenticate a user with password.js

Currently, I am working on implementing validation using passport.js and ES6. Below is the validation function that I have created: passport.use(new BasicStrategy( function(login, password, callback) { User.findOne({ login: login }).select(&a ...

There is an error appearing in my .ts code: [ts] The property 'name' is not found in type 'any[]'

While my coding is working fine and data is showing on the page, there seems to be an error occurring in the VSE editor. It is showing something like this: [ts] Property 'name' does not exist on type 'any[]'. This is a snippet of my ...

Tips on maintaining and hiding the vertical scrollbar when a popup is open, alongside the navigation bar positioned at the top of the page

After reviewing this pen, my goal is to create a popup that maintains access to the navigation bar (hence avoiding Bootstrap's Modal). However, I am facing the challenge of keeping the scrollbar visible while preventing scrolling in the background whe ...

Ways to update the content of a NodeList

When I execute this code in the console: document.querySelectorAll("a.pointer[title='Average']") It fetches a collection of Averages, each with displayed text on the page: <a class="pointer" title="Average" onclick="showScoretab(this)"> ...

Nested pages in the NextJS router do not properly highlight the active menu item

I am currently working with NextJS and facing an issue with setting active menu items using the router. While the 'top level' pages behave as expected, any page under a top level page does not get set as active. router.pathname == "/profile& ...

Axios cancel token preemptively cancelling request before it is initiated

Currently, I am working on implementing cancellation of axios calls in my project. After reviewing the axios documentation, it appears to be quite straightforward, which can be found here. To begin, I have defined some variables at the top of my Vue compo ...

Issue with Ionic displaying data from AngularJS $http.get request

Having just started learning AngularJS, I have followed tutorials on YouTube and read the documentation, but I am struggling to display data from an API using the $http.get() request. Here is my JavaScript and HTML code: var exampleApp= angular.modul ...

How do I see all the implementations of a Vue 3 component when using Volar in VS Code?

Is there a more efficient method for identifying all the instances of a <script setup> component used in various parts of my application? Neither the Go to Implementations nor Go to References options seem to work, so currently I am resorting to man ...

The positioning of the input is being altered by the bootstrap-vue formatter

Is there a way to replace whitespaces with underscores in the file name input of bootstrap-vue without changing the cursor position? If I add a white space not at the end of the input, the formatter moves the cursor to the end. How can I achieve this? I a ...

Route.get() function is expecting a callback function, but instead received a string object

Having searched through similar posts, I am unsure and lack the experience to apply the suggested resolutions to my project. I recently built a basic app with two main routes as part of a Udemy course, but I am struggling with the following error: "Route.g ...

The dynamic functionality of the Bootstrap React Modal Component seems to be malfunctioning

I'm encountering an issue with React Bootstrap. I'm using the map function in JavaScript to iterate through admins. While all values outside the modal display correctly from the admins array, inside the modal only one standard object from the arr ...

Creating a collection by gathering data from interactive fields with the help of AngularJS

I have a project to create an attendance system for employees. The system requires me to track the attendance status of each employee by generating a dynamic form with text input fields and checkboxes using angularjs ng-repeat inside a table. This form wil ...

Error: Laravel Pusher Authorization Failed

My events are not working properly on my laravel 7.x setup with pusher and laravel-echo. I have double-checked everything and even set the broadcast driver to pusher in the .env file, but still getting a 401 error. If anyone has any insights or solutions, ...

The ngModel directive automatically clears the checkbox's Checked status

Currently, my Angular code is set up to validate a checkbox using ng-model: <input type="checkbox" name="news1" value="news1" ng-model="news" <c:if test="${xxxx == yes'}">checked="checked"></c:if>> <label ng-click="news1();"&g ...

Troubleshooting V-model errors within VueJS components

Just dipping into VueJS and trying out a chat feature from a tutorial. I noticed the tutorial uses v-model in a component, but when I replicate it, the component doesn't display on the screen and the console throws a "text is not defined" error. Strug ...

What is the best way to ensure that the user interface stays updated with alterations made to

I am currently studying various front end design patterns, and I repeatedly come across the idea of implementing a virtual shopping cart in a shopping cart scenario. The suggestion is to have the user interface actively monitor any changes to the cart and ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

Express JS form validation using hapi/Joi fails to accurately validate the input data in forms

I am currently facing an issue with my form validation using the hapi/Joi package. The problem is that the schema keys are all taking the value of "undefined", which results in the first validation error being returned. How can I resolve this issue? Additi ...