V-Model
V-model is a Vue directive that creates a two-way data binding between a form input and a data property. It allows you to bind the value of an input element to a data property and automatically update that property when the input value changes. v-model is shorthand for using both v-bind and v-on together.
To use v-model on an input element, you just need to add the directive to the element and bind it to a data property. For example:
<template> <input v-model="message"></template><script>export default { data() { return { message: 'Hello World' } }}</script>
In this example, the value of the input element is bound to the message data property, so when the input value changes, the message property is updated, and when the message property changes, the input value changes.
Compatability
v-model works with most form input elements, including text inputs, checkboxes, radio buttons, select elements, and textareas. However, some input elements may require additional configuration.
Text Inputs
v-model works out of the box with text inputs, so you can simply add the directive to a text input element and bind it to a data property.
Checkboxes
To use v-model with a checkbox, you need to bind the v-model directive to the value attribute of the checkbox, and add a
<template> <input type="checkbox" v-model="isChecked" :value="true"></template><script>export default { data() { return { isChecked: false } }}</script>
Radio Buttons
To use v-model with radio buttons, you need to give each radio button the same name attribute and bind the v-model directive to the value of the selected radio button. For example:
<template> <input type="radio" v-model="selectedOption" value="option1"> <input type="radio" v-model="selectedOption" value="option2"> <input type="radio" v-model="selectedOption" value="option3"></template><script>export default { data() { return { selectedOption: 'option1' } }}</script>
Select Elements
To use v-model with a select element, you need to bind the v-model directive to the value attribute of the select element. For example:
<template> <select v-model="selectedOption"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select></template><script>export default { data() { return { selectedOption: 'option1' } }}</script>
Modifiers
v-model also supports a number of modifiers that can be used to modify the behavior of the two-way binding. Some of the most commonly used modifiers include:
- .lazy - This modifier causes the data property to be updated only when the input element loses focus, instead of updating it immediately when the input value changes.
- .number - This modifier automatically converts the input value to a number before updating the data property.
- .trim - This modifier automatically trims whitespace from the input value before updating the data property.