How to Use v-model in Vue: Simple Binding Explained
In Vue,
v-model creates a two-way binding between a form input and a data property, syncing user input with your component's state automatically. Use v-model on input elements like <input>, <textarea>, or custom components to keep data and UI in sync.Syntax
The v-model directive binds a data property to an input element, enabling two-way data flow. The syntax is <input v-model="propertyName" />. Here, propertyName is a data variable in your Vue component. When the user types, the variable updates; when the variable changes, the input updates.
html
<input v-model="message" placeholder="Type something" />
Output
An input box where typing updates the 'message' data property and changes to 'message' update the input box.
Example
This example shows a text input bound to a message data property. Typing in the box updates the message below in real time.
vue
<template>
<div>
<input v-model="message" placeholder="Enter text" />
<p>You typed: {{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('')
</script>Output
An input box and below it text that updates live as you type.
Common Pitfalls
One common mistake is using v-model on a non-reactive property or forgetting to declare the data property, which breaks reactivity. Another is trying to use v-model on custom components without emitting the correct update event. Also, avoid using v-model on read-only inputs.
vue
<!-- Wrong: no reactive property --> <input v-model="text" /> <!-- Right: declare reactive property --> <script setup> import { ref } from 'vue' const text = ref('') </script>
Quick Reference
| Feature | Description |
|---|---|
| Basic usage | v-model="dataProperty" binds input to data |
| Supported elements | input, textarea, select, custom components |
| Two-way binding | Updates data on input and input on data change |
| Custom components | Use modelValue prop and update:modelValue event |
| Modifiers | Use .lazy, .number, .trim for input control |
Key Takeaways
Use
v-model to bind input elements to reactive data for automatic syncing.Declare reactive properties with
ref or reactive to enable v-model.For custom components, implement
modelValue prop and emit update:modelValue event.Avoid using
v-model on non-reactive or read-only elements.Use modifiers like
.lazy, .number, and .trim to customize input behavior.