Binding the inputs to local state

The purpose of forms in a web application is to capture some user input and be able to do something with it. In our example, we still don't have any way to access the user's input with JavaScript for our Vuetiful plans—so, let's start with that.

Please note that you do not necessarily have to wrap up your form's data inside a secondary object, but, I have found it to be cleaner—especially when you start adding other data properties to your component, which may not necessarily be related to your form.

Create a new data property on the instance of your App.vue file. Inside of it, we're going to declare a form object, which will, in turn, hold a property for each one of our inputs:

<script>
export default {
name: 'app',
data() {
return {
form: {
firstName: '',
lastName: '',
email: ''
}
}
}
}
</script>

For us to bind our inputs' values to our internal state, we need to make use of Vue's v-model attribute. So, let's add v-model to each of our inputs. That way, whenever the user types in or deletes information, the value of the input element will be bound to our data property.

Remember that v-model is not a magical attribute. It is a shorthand for two things:

  • It binds the input event of our input boxes:
v-on:input="form.name = $event.target.value"
  • It binds the value attribute to our data property:
 v-bind:value="form.firstName"

Go ahead and add v-model to all of our inputs: 

...
<div class="form-group">
<label>First Name:</label>
<input
v-model="form.firstName"
type="text"
class="form-control"
>
</div>
<div class="form-group">
<label>Last Name:</label>
<input
v-model="form.lastName"
type="text"
class="form-control"
>
</div>
<div class="form-group">
<label>Email:</label>
<input
v-model="form.email"
type="email"
class="form-control"
>
</div>

The following screenshot shows the Vue developer tools displaying the two-way data binding between our form and the internal state in our data:

Great job! Now, this isn't super impressive, but we are building the foundations for things to come.

In the following section, we're going to look at how to handle the form being submitted and sent to an API endpoint.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset