tezvyn:

Vue's v-model: Two-Way Binding Made Simple

AI-drafted, machine-checkedSource: vuejs.orgbeginner

v-model creates a two-way binding that synchronizes form inputs with your JavaScript data. Use it on any form element like an input or textarea. The footgun: it ignores initial HTML attributes; your JavaScript state is always the single source of truth.

WHY IT EXISTS To eliminate the boilerplate of manually syncing form inputs with application state. Without it, you must bind an element's value and listen for its input events separately for every single form field, which is repetitive, verbose, and error-prone.

THE MENTAL MODEL Think of v-model as a shortcut for a two-way conversation between your UI and your data. Normally, data flows one way from your script to the template. v-model opens a return channel, so when a user types into an input, the change flows back to your script's data property automatically. It's syntactic sugar that bundles a prop binding and an event listener into one clean directive.

HOW IT WORKS Vue expands v-model into a property binding and an event listener at compile time. The exact pair depends on the element. For text inputs and textareas, <input v-model="searchText"> becomes <input :value="searchText" @input="searchText = $event.target.value">. For checkboxes and radio buttons, it uses the checked property and the change event. For select dropdowns, it's the value property and change event. Vue handles this logic so you don't have to.

WHEN TO USE IT Use v-model whenever you need to capture user input from a form. It is the idiomatic, go-to solution in Vue for text fields, textareas, checkboxes, radio buttons, and select dropdowns. It is also the standard way to enable two-way binding on your own custom components.

WHEN NOT TO USE IT Avoid v-model if you need to react to IME composition events (e.g., for Chinese or Japanese input), as it only updates after composition is complete. In that specific case, you must manage the :value binding and @input listener yourself to handle intermediate states. If you need to run complex logic on the input value before updating state, a custom event handler can be clearer.

ONE CANONICAL EXAMPLE To bind a text input to a message data property, you simply write <input v-model="message">. If you declare message in your script with an initial value of "Hello Vue", the input field will render with "Hello Vue" pre-filled. When the user types "Hello World" into the input, the message property in your script will instantly update to "Hello World" without any extra code.

Read the original → vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.