Vue v-model Directive

Welcome to The Coding College! In this guide, we’ll dive deep into Vue.js’s v-model directive—a powerful tool for achieving two-way data binding between form inputs and Vue’s data properties. By the end of this guide, you’ll understand how v-model works, how to use it with various input types, and best practices for efficient and clean form handling.

What is v-model?

The v-model directive in Vue.js provides two-way data binding between a form input or component and the Vue instance’s data. When the user updates the input, the data is automatically synchronized, and vice versa.

Example

<div id="app">
  <label for="name">Name:</label>
  <input id="name" v-model="name" type="text">
  <p>Hello, {{ name }}!</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      name: ''
    }
  });
</script>

Explanation:

  • The v-model directive binds the name data property to the input field.
  • Changes in the input field update name, and updates to name reflect in the input.

Syntax of v-model

The v-model directive is used on input, textarea, select elements, and even custom components.

<input v-model="property">
  • Binding direction: Two-way.
  • Event handled: Automatically listens for the appropriate input events.

Supported Input Types

Text Input

<input v-model="text" type="text">

Textarea

<textarea v-model="message"></textarea>

Checkbox

Single Checkbox

<input v-model="isChecked" type="checkbox">

Multiple Checkboxes

<div>
  <input type="checkbox" v-model="selected" value="Option 1"> Option 1
  <input type="checkbox" v-model="selected" value="Option 2"> Option 2
  <p>Selected: {{ selected }}</p>
</div>

Radio Buttons

<div>
  <input type="radio" v-model="picked" value="Option 1"> Option 1
  <input type="radio" v-model="picked" value="Option 2"> Option 2
  <p>Picked: {{ picked }}</p>
</div>

Select Dropdown

<select v-model="selected">
  <option disabled value="">Select an option</option>
  <option>Option 1</option>
  <option>Option 2</option>
</select>

Modifiers for v-model

Vue provides several modifiers to enhance the functionality of v-model:

1. .lazy

Updates the data property only on the change event instead of the input event.

<input v-model.lazy="name" type="text">

2. .number

Automatically converts the input value to a number.

<input v-model.number="age" type="number">

3. .trim

Removes whitespace from the beginning and end of the input.

<input v-model.trim="username" type="text">

Two-Way Binding with Custom Components

You can also use v-model with custom components by defining a value prop and emitting the input event.

Example:

<template>
  <div>
    <input :value="value" @input="$emit('input', $event.target.value)">
  </div>
</template>

<script>
export default {
  props: ['value']
};
</script>

Usage:

<custom-input v-model="customValue"></custom-input>
<p>{{ customValue }}</p>

Best Practices for Using v-model

  1. Use .trim and .number
    • Clean input data and ensure numeric values are correctly handled.
  2. Handle Validation
    • Use v-model with computed properties or watchers for real-time validation.
  3. Avoid Overbinding
    • Use v-model only where two-way binding is necessary.
  4. Use Modifiers for Performance
    • For large forms, leverage .lazy to reduce unnecessary updates.

Advanced Example: Dynamic Forms with v-model

<div id="app">
  <form @submit.prevent="handleSubmit">
    <div v-for="(field, index) in fields" :key="index">
      <label :for="field.name">{{ field.label }}</label>
      <input :id="field.name" v-model="field.value" :type="field.type">
    </div>
    <button type="submit">Submit</button>
  </form>
  <p>Form Data: {{ fields }}</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      fields: [
        { name: 'name', label: 'Name', type: 'text', value: '' },
        { name: 'email', label: 'Email', type: 'email', value: '' }
      ]
    },
    methods: {
      handleSubmit() {
        console.log(this.fields);
      }
    }
  });
</script>

Explanation:

  • v-model dynamically binds form fields, making it easy to create reusable and dynamic forms.

Conclusion

The v-model directive is an essential tool in Vue.js for creating interactive and responsive user interfaces. Its ability to bind data seamlessly with various input types makes it an invaluable feature for form handling.

For more insights and tutorials on Vue.js and other programming topics, visit The Coding College. We’re here to help you master the art of coding!

Leave a Comment