v-model on inputs
Different input types bind differently, and modifiers like .trim, .number and .lazy fine-tune the behaviour.
In this page:
Syntax
<input v-model.trim="text">
<input v-model.number="number">
<textarea v-model="text"></textarea>
v-model on inputs
Text inputs and textareas bind strings. Add .trim to strip whitespace, .number to convert to a number and .lazy to update on change instead of input. Note that multi-line text in a textarea uses v-model, not interpolation inside the tags.
Note:
type="number" inputs still give strings unless you add .number.
Example: v-model on inputs
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<input v-model.trim="title">
<input v-model.number="age">
<textarea v-model="bio"></textarea>
<p>[{{ title }}] {{ typeof age }} {{ age }}</p>
</div>
<script>
Vue.createApp({ data() { return { title: "", age: 0, bio: "" }; } }).mount("#app");
const [t, a] = document.querySelectorAll("input");
t.value = " padded "; t.dispatchEvent(new window.Event("input"));
a.value = "42"; a.dispatchEvent(new window.Event("input"));
Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: [padded] number 42
console: [padded] number 42
-->
Live Example
Related Topics
Common Mistakes
- Interpolating inside textarea
- Forgetting .number and comparing strings
- Using .lazy and expecting live updates
Chapter Summary
- .trim removes whitespace
- .number converts to a number
- .lazy updates on change
- textarea uses v-model
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: