Form Handling

The v-modelopen in new window directive creates two-way data binding with form inputs, text areas, and select elements making it easy to set and retrieve from an HTML form and user input.

The v-model directive updates different properties and emits different events depending on the input element that is using it.

  • The text inputs and textarea elements use the value property and input event
  • The checkbox inputs and radio buttons use checkedproperty andchange` event;
  • select fields use value as a prop and change as an event.

Basic Usage

The v-model directive to create two-way data bindings on form input, text area, and select elements. This means as the page loads the form input will be pre-filled with the values of the Vue data. Then as the user makes changes to the forms, the Vue data will also change.

<div id="app">
  <p>{{ message }}</p>
  <input type="text" v-model="message">
</div>
const app = Vue.createApp({
  data: function () {
    return { message: 'Hello' }
  }
})

const vm = app.mount('#app')

Form Handling

Because it can be used on any form input, the v-model directive makes it is easy to handle forms.

NOTE

When handling a form with Vue, you will rarely want the form to cause a page refresh. There it is best to add the .prevent modifier to the v-on:submit directive on the form tag.

The following example demonstrates how you can handle a form using the v-on and v-model directives. As you update the form, the Request will change to match the changes.

const app = Vue.createApp({
  data: function () {
    return {
      referrers: ['TV', 'Radio', 'Google', 'Other'],
      email: '',
      referrer: '',
      accepted: false
    }
  }
})

const vm = app.mount('#app')
<div id="app">
  <form @submit.prevent>
    <div class="form-group">
       <input 
        type="email" 
        class="form-control" 
        placeholder="Your Email" 
        v-model="email">
    </div>
    <div class="form-group">
        <select 
          class="form-control" 
          v-model="referrer">
          <option value="">How did you hear about us?</option>
          <option 
            v-for="referrer in referrers" 
            :value="referrer">
            {{ referrer }}
          </option>
        </select>
    </div>
    <div class="form-group">
      <div class="form-check">
        <input 
          id="accept" 
          class="form-check-inline" 
          type="checkbox" 
          v-model="accepted">
        <label 
          class="form-check-label" 
          for="accept">
          Accept the terms an conditions
        </label>
      </div>
    </div>
  </form>
  
  <div class="card mt-5">
    <div class="card-header">Request</div>
    <div class="card-body">
      <p>Email: <strong>{{ email }}</strong></p>
      <p>Referrer: <strong>{{ referrer }}</strong></p>
      <p>Accepted: <strong>{{ accepted }}</strong></p>
    </div>
  </div>
</div>