vue

How to submit a form in VueJS


In this article, you are going to learn about how to submit a form in VueJS.

Working with for is an essential part of any website development. To take user’s information or any information from the client side, using form is very handy approach. You can easily create a form in VueJS. In general, when a user submit a form with specific information, the data was saved into the back-end server. But here for learning purposes we will not use any backend technology and the data will be displayed in the browser.

In VueJs, To work with form and submit a form with proper data you need to use v-model. This will bind your form data. Let’s see the below example where we build a simple form submit option in which a student can send his name and age the the information will be visible in the browser also.

Template:

<template>
    <form @submit="onSubmit" class="add-form">
    <div class="form-control">
      <label>Name</label>
      <input type="text" v-model="name" name="name" placeholder="Enter Your Name" />
    </div>
    <div class="form-control">
      <label>Age</label>
      <input
        type="text"
        v-model="age"
        name="age"
        placeholder="Enter Your Age"
      />
    </div>
    <input type="submit" value="Save Information" class="btn btn-block" />
  </form>
</template>

Here in the Vue Template we have created a form and use v-model to bind the data. Let’s see our script where we wrote the JavaScript code.

Script:

<script>
    export default {
        name : 'AddInformation',
        data (){
            return {
                name : '',
                age : '',
            }
        },
        methods : {
            onSubmit(e){
                e.preventDefault()
                if(!this.name){
                    alert('Please Add a Name')
                    return
                }
                const NewInformation = {
                    id: Math.floor(Math.random() * 100000),
                    name : this.name,
                    age : this.age,
                    reminder : this.reminder
                }
                this.$emit('add-information', newInformation)
                this.name = ' ',
                this.age = ' '
            }
        }
    }
</script>

Here, we write the logic for make things work in our AddInformation component and export it. Finally we import this component into our main vuejs file. Let’s see the output below:

Output:

We add name and age and click on the save information button let’s see the output if it shows the data properly or not in the below:

You can see that the name and age has been showing successfully in the below and also the form data cleared. That’s mean our program for form submit is working perfectly. we have use some CSS to give it a better UI but it is not our goal and also not important. You may set your own CSS styles and this is how you can submit a form data in VueJS.


Share on social media

//