The v-model Directive
The v-model directive links a form input to a piece of state. It keeps the input value and the state in step with each other.
Two-way link
The input shows the name. Typing Ada updates the state.
<input v-model="name">
<p>Hello {{ name }}</p>A number input
With 12 typed in, the page shows Age: 12.
<input type="number" v-model="age">
<p>Age: {{ age }}</p>A text area
With Hi typed in, the note shows Hi.
<textarea v-model="note"></textarea>
<p>{{ note }}</p>Example
<script setup>
import { ref } from 'vue'
const name = ref('')
const age = ref(0)
const note = ref('')
</script>
<template>
<div>
<input v-model="name" placeholder="Type your name">
<p>Hello {{ name }}</p>
</div>
</template>
Key points
- v-model sits on a form input, like an input box.
- It reads the current state value into the input.
- It writes each change from the input back into the state.
- The state needs a ref, so Vue can track the change.
- The page updates at once when the state changes.
In this example, name starts as an empty ref. The script also makes age and note refs for the other inputs. The input uses v-model to link to name. The paragraph shows Hello plus the name. Typing in the input updates name at once. The paragraph updates with it.
Note
v-model needs a form input, so it does not work on a paragraph.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does v-model do on an input?