Processing a Form with Vue.js

Processing a form can be a long and tedious task when using vanilla JavaScript or jQuery. While those tools can help to make your AJAX forms very clean, and provide your user with immediate feedback and validations, writing the code can become a bit convoluted.

Processing forms with Vue however is an easy task. With data-binding and reactivity, we can quickly process a form since all the inputs are bound to the variables we have.

Let's take a look at processing a form with vanilla JavaScript and then see how easy Vue makes the job.

For this tutorial, we won't have any backend service to process the form; we'll just be alerting when the form is processed. You can hook in your own backends later.

Here is the full code to process a form with Vue. The main parts of the code to notice is the:

  • v-model binding each input to a data variable
  • @submit.prevent to submit the form and prevent the default form submission behavior (page refresh)
html
<template>
  <form @submit.prevent="submitForm">

    <!-- username input -->
    <input type="text" v-model="username" placeholder="Username">

    <!-- email input -->
    <input type="text" v-model="email" placeholder="Email">

    <!-- password input -->
    <input type="password" v-model="password" placeholder="Password">

    <!-- submit button -->
    <button type="submit">Submit</button>

  </form>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      email: '',
      password: '',
    }
  },
  methods: {
    // submit the form to our backend api
    async submitForm() {
      const res = await fetch('/backend-api', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },

        // pass in the information from our form
        body: JSON.stringify({
          username: this.username,
          email: this.email,
          password: this.password,
        }) 
      });
    } 
  }
}
</script>

We start by creating our HTML and the data() for the form.

html
<template>
  <form>

    <!-- username input -->
    <input type="text" placeholder="Username">

    <!-- email input -->
    <input type="text" placeholder="Email">

    <!-- password input -->
    <input type="password" placeholder="Password">

    <!-- submit button -->
    <button type="submit">Submit</button>

  </form>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      email: '',
      password: '',
    }
  }
}
</script>

Next up, we need to bind these two variables to our inputs. Update the inputs to have the v-model directive.

html
<!-- username input -->
<input type="text" v-model="username" placeholder="Username">

<!-- email input -->
<input type="text" v-model="email" placeholder="Email">

<!-- password input -->
<input type="password" v-model="password" placeholder="Password">

We'll use v-model to bind a data variable to an input. Now whenever this input changes, it is immediately reflected in our Vue instance. It's automatically bound thanks to Vue!

We have our data grabbed and bound. The last thing we need to take care of is listening to the submit event and submitting the form.

Vue lets us do this easily since it has a v-on directive where we can listen to submit like so: v-on:submit

html
<form v-on:submit.prevent="submitForm">

<!-- we can shorthand v-on: with the @ -->
<form @submit.prevent="submitForm">

We are also adding the .prevent to prevent the default form submission behavior. This is important because an HTML form will try to refresh the page by default and we want to stop that behavior.

We have also told the form to use submitForm. We are saying "when the form is submitted, use the submitForm method".

Let's create that now. Inside our Vue instance, let's add the methods and our new processForm method:

html
<script>
export default {
  data() {
    // ...
  },
  methods: {
    // submit the form to our backend api
    async submitForm() {
      const res = await fetch('/backend-api', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },

        // pass in the information from our form
        body: JSON.stringify({
          username: this.username,
          email: this.email,
          password: this.password,
        }) 
      });
    } 
  }
}
</script>

We are using a fetch here to send the information of our form to our backend API endpoint. We are using POST because we are sending information to the server. We are using application/json as the content type because we are sending JSON data. We are using JSON.stringify to convert our data to JSON.

To access our data variables from within methods, we can use the this. syntax. this refers to the parent Vue instance and that gives us direct access to our data variables.

Our form is ready for processing! If we ever needed to bind new input values, we'd just need to create the inputs and add the variable to our data.

While this was a simple example, I hope you can see the value of Vue in processing forms. Vue handles all of the boring code for grabbing, listening, and injecting. Now we can focus on the code that we want to focus on.

From here, you can add in validation and other features to your forms.

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)