In Vue.js, the v-model directive is a two-way data binding directive used primarily with form input elements.
It creates a binding between the value of an input field and a Vue.js data property.
This means that changes made to the input field by the user will automatically update the associated data property, and changes made to the data property will update the input field in the UI.
Here's a Syntax of how v-model used in HTML elements:
<!-- Binding to a simple property --> <input v-model="propertyName"> <!-- Binding to an array --> <input v-model="array"> <!-- Binding to an object attribute key--> <input v-model="objectName.attributeName"> <!-- Binding to a computed property --> <input v-model="computedPropertyName">
the "message" data property is bound to the value of the text input field.
When the user types into the input field, the "message" property is updated accordingly.
Similarly, if the value of the "message" property changes programmatically, the input field will be updated in the UI.
<input v-model="message" type="text">
Similar to the text input example, the "message" data property is bound to the value of the textarea element.
Changes made to the textarea by the user or programmatically will update the "message" property, and vice versa.
<textarea v-model="message"></textarea>
the "checked" data property is bound to the "checked" state of the checkbox input.
When the user checks or unchecks the checkbox, the "checked" property will be updated accordingly.
<input v-model="checked" type="checkbox">
the "selected" data property is bound to the "selected" value of the radio button inputs.
Only one radio button can be "selected" at a time, and the "selected" property will be updated with the value of the selected radio button.
<input v-model="selected" type="radio" value="option1"> <input v-model="selected" type="radio" value="option2">
The "selected" data property is bound to the "selected" option in the dropdown menu.
When the user selects an option, the "selected" property will be updated with the value of the "selected" option.
<select v-model="selected"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> </select>
v-model provides a convenient way to implement two-way data binding for form input elements in Vue.js applications.
It simplifies the process of syncing data between the UI and Vue component's data model, making form handling more intuitive and efficient.