{{announcement.body}}
{{announcement.title}}

Vue Tutorial 5 — Form Data Binding

DZone 's Guide to

Vue Tutorial 5 — Form Data Binding

In the fifth edition of this series, we discuss how to use form data binding in Vue in order to keep track of form submissions from users.

· Web Dev Zone ·
Free Resource

boat-docked-with-rope

Granny now wants us to help her make a list of all the guests attending the party. She could use pen and paper, but her grandson is a programmer and she wants a Vue app. 

In this tutorial, we’ll accept user input (information about a guest) and display it in the list, similar to when we displayed the list of groceries. However, today we’ll use the  v-model directive to create two-way data bindings on the form input. 

Note: You can find parts one, two, three, and four at their respective links. 

You may also like: Getting Started With VueJS.

Two-Way Data Bindings

 V-model directive automatically updates a DOM element based on the type of the input it is assigned to. It can distinguish between input, textarea, or select an element without any specification from us.

Here's the spec from Granny for the Vue app:

  • Add a persons full name (input).
  • Add check for whether the guest has RSVP’d or not (single checkbox)
  • Add a selection for table number (select).
  • Allow to specify any special dietary requirements (multi checkbox).

Let’s begin by defining the name input element with a v-model directive.

<div class="container">
    <div class="row">
        <div class="col">
            <div id="app" class="col-md-6 offset-md-3 my-5">
                <div class="form-group">
                    <label for="name">Full Name</label>
                    <input id="name" name="name" class="form-control" v-model="name"/>
                </div>
                <div class="btn btn-block btn-success">Add {{ name }} to the list</div>
            </div>
        </div>
    </div>
</div>


We will also have to define a corresponding data property

var app = new Vue({
    el: "#app",
    data: {
        name: “"
   },
    methods: {}
})


With those two elements in place, our form DOM element is bound to the data property. Once any of those is updated, so is the other one. 

Adding a name to the list

Adding a name to the list

Note: If you programmed in React before, you have probably noticed at this stage that data is very similar to React’s state. 

Bootstrap

You noticed that the above form looks quite nice. It’s because I’ve imported Bootstrap to our project. If you’re not familiar with Bootstrap please have a quick read about it here — it will change the way you build your websites. In order to import to your project run the following

 npm install bootstrap 


Then, simply import it to your page and Bob’s your uncle.

<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css"/>


Now, I’d like for you to build the form in line with Granny’s spec. This is what the completed form should look like when you’re done.

Adding reservation functionality

Adding reservation functionality

Here’s what my HTML looks like. I encourage you to type it up yourself, step-by-step rather than mindlessly copying the block of code. Trust me, you’ll be all the better for it. It’s okay if your code differs once you get the similar look of the form. 

 <div class="form-group">
                    <label for="name">Full Name</label>
                    <input id="name" name="name" class="form-control" v-model="name"/>
                </div>

                <div class="form-group form-check">
                    <input type="checkbox" id="checkbox" class="form-check-input" v-model="confirmed"/>
                    <label for="checkbox" class="form-check-label">RSVP</label>

                </div>

                <div class="form-group">
                    <label for="tableNumber" class="form-check-label">Table Number</label>
                    <select id="tableNumber" v-model="tableNumber" class="form-control">
                        <option disabled value="">Table number</option>
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                        <option>5</option>
                        <option>6</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Dietary Requirements</label>
                    <br>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" id="vegetarian" value="vegetarian"
                               v-model="allergies">
                        <label class="form-check-label" for="vegetarian">Vegetarian</label>
                    </div>
                    <div class="form-check form-check-inline">

                        <input class="form-check-input" type="checkbox" id="vegan" value="Vegan" v-model="allergies">
                        <label class="form-check-label" for="vegan">Vegan</label>

                    </div>
                    <div class="form-check form-check-inline">

                        <input class="form-check-input" type="checkbox" id="dairyFree" value="Dairy-Free"
                               v-model="allergies">
                        <label class="form-check-label" for="dairyFree">Dairy-Free</label>

                    </div>
                    <div class="form-check form-check-inline">

                        <input class="form-check-input" type="checkbox" id="glutenFree" value="Gluten-Free"
                               v-model="allergies">
                        <label class="form-check-label" for="glutenFree">Gluten-Free</label>

                    </div>

                </div>

                <div class="btn btn-block btn-success" >Add {{ name }} to the list</div>


Display the List of Added Elements

Now that we have a form to gather all of the information about each distinguished guest, we should probably store it and display it in a table. 

Since Granny expects for many guests to arrive, it will make sense to store each guest in an array. Let’s hook up a method to the button.

 <div class="btn btn-block btn-success" v-on:click="addGuest">Add {{ name }} to the list</div>


methods: {
    addGuest: function () {
        console.log(`Adding guest ${this.name} ${this.confirmed} ${this.tableNumber} ${this.allergies}`)
        let guest = {name: this.name, confirmed: this.confirmed, tableNumber: this.tableNumber, allergies: this.allergies}
        this.guests.push(guest)

        this.name = ''
        this.confirmed = false
        this.tableNumber = ''
        this.allergies = []
    }
}


This method creates a new guest object, populates it with the input, and then clears the form to allow for subsequent guests to be added. Nifty! 

Remember to add the guests array in the data.

 guests: [] 

Every new guest is stored in this array. Let's use the v-for directive to display a table of all our guests.

<table class="table table-striped mt-5">
                    <thead class="thead-dark">
                    <tr>
                        <th scope="col">Full Name</th>
                        <th scope="col">RSVP</th>
                        <th scope="col">Table</th>
                        <th scope="col">Dietary Requirements</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(guest, index) in guests">
                        <td>{{ guest.name}}</td>
                        <td>{{ guest.confirmed }}</td>
                        <td>{{ guest.tableNumber }}</td>
                        <td>{{ guest.allergies }}</td>
                    </tr>
                    </tbody>
                </table>


If you followed the steps above correctly, your guest management app should work well. You and Granny are ready to appropriately plan this party. 

Finished form and table

Finished form and table

Conclusion

In this tutorial, we learned about the v-model, which is a powerful directive available to us in Vue. We have then implemented a simple app that deployed all of the things we’ve learned about Vue so far.

The code for this tutorial is available here


Further Reading

Topics:
vuejs 2 ,vuejs 2 tutorial ,bootstrap 4 ,web dev ,react ,spa ,dom ,textarea ,v-model ,v-for

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}