0
0
VueHow-ToBeginner · 3 min read

How to Use v-model with Input in Vue 3

Use v-model on an input element to create two-way binding between the input's value and a Vue component's data property. This means when the user types, the data updates automatically, and if the data changes, the input shows the new value.
📐

Syntax

The v-model directive binds the input's value to a data property and listens for input events to update that property. It simplifies syncing user input with your component's state.

  • v-model="propertyName": Binds the input value to propertyName.
  • The input updates the property on user input.
  • Changing the property updates the input's displayed value.
vue
<input v-model="message" placeholder="Type here">
💻

Example

This example shows a text input bound with v-model. When you type, the message below updates live. Changing the message in code also updates the input.

vue
<template>
  <div>
    <input v-model="message" placeholder="Type your message" />
    <p>Your message: {{ message }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const message = ref('')
</script>
Output
Your message: (shows what you type in the input)
⚠️

Common Pitfalls

Common mistakes when using v-model with inputs include:

  • Not initializing the bound data property, causing errors or no updates.
  • Using v-model on a non-input element without proper modifiers.
  • Trying to use v-model with complex objects without handling reactivity properly.

Always initialize your data property and use ref or reactive for reactivity.

vue
<!-- Wrong: no initial value -->
<input v-model="message" />

<script setup>
// message is not defined or initialized
</script>

<!-- Right: initialize message -->
<script setup>
import { ref } from 'vue'
const message = ref('')
</script>
📊

Quick Reference

Tips for using v-model with inputs:

  • Use ref to create reactive data for simple values.
  • Use v-model on input, textarea, and select for easy two-way binding.
  • For checkboxes and radio buttons, v-model works with booleans and arrays.
  • Use modifiers like .trim or .number to process input values.

Key Takeaways

Use v-model on inputs to bind their value to reactive data for automatic syncing.
Always initialize the data property you bind with v-model using ref or reactive.
The input updates the data on user input, and data changes update the input display.
Use modifiers like .trim or .number to control input value formatting.
Avoid using v-model on unsupported elements or without proper data initialization.