v-model helps keep your data and input fields in sync automatically. When you change the input, the data updates, and when the data changes, the input updates.
0
0
v-model for two-way binding in Vue
Introduction
You want to update a form input and keep the data updated without writing extra code.
You need to show a value in an input box and let users change it easily.
You want to build interactive forms like checkboxes, text fields, or selects that reflect your data.
You want to simplify handling user input in your Vue components.
Syntax
Vue
<input v-model="dataProperty" />The v-model directive binds the input's value to a data property.
It works with many input types like text, checkbox, radio, and select.
Examples
Bind a text input to the
name data property.Vue
<input v-model="name" />Bind a checkbox to the
isChecked boolean property.Vue
<input type="checkbox" v-model="isChecked" />
Bind a select dropdown to
selectedOption.Vue
<select v-model="selectedOption"> <option value="A">Option A</option> <option value="B">Option B</option> </select>
Sample Program
This Vue component uses v-model to bind the input field to the username data. When you type in the input, the paragraph below updates automatically to show the current username.
Vue
<template>
<div>
<label for="username">Username:</label>
<input id="username" v-model="username" />
<p>Your username is: {{ username }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const username = ref('')
</script>OutputSuccess
Important Notes
v-model automatically listens for input events and updates the data.
For custom components, you can use v-model with modelValue and update:modelValue events.
Remember to initialize your data property (like using ref('') for strings) so Vue can track it.
Summary
v-model links input fields and data for easy two-way binding.
It works with many input types and updates automatically.
Use it to simplify forms and user input handling in Vue.