Forms are an essential part of web applications, enabling users to interact with and input data into an application. Vue.js simplifies the process of handling forms by introducing the powerful v-model directive, providing a seamless two-way binding between input elements and Vue instances. In this guide, we will explore the versatility of the v-model directive and its application in various scenarios.
Two-Way Binding with v-model
The v-model directive in Vue.js establishes a bidirectional connection between input elements and Vue instance data. Let's delve into a basic example to understand the magic of two-way binding.
<div id="app">
<input type="text" v-model="inpText">
<p>{{ inpText }}</p>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
inpText: 'Initial text'
}
}
})
app.mount('#app')
</script>
In this example, any change in the input field updates the Vue instance data (inpText), and vice versa. This elegant two-way binding simplifies data synchronization between the UI and application state.
Dynamic Checkbox for User Interaction
Let's enhance our form by adding a dynamic checkbox to mark items as "important." The following example showcases the simplicity of incorporating a dynamic checkbox using v-model.
<div id="app">
<form>
<p>
Important item?
<label>
<input type="checkbox" v-model="itemImportant">
{{ itemImportant }}
</label>
</p>
</form>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
itemImportant: false
}
}
})
app.mount('#app')
</script>
In this example, the checkbox's state is dynamically reflected in the text next to it, providing users with instant feedback.
Marking Found Items in a Shopping List
Now, let's implement a feature where users can mark items as "found" in a shopping list. This dynamic functionality involves clicking on items to toggle their status between "found" and "not found." Items marked as "found" are visually differentiated in the list.
<div id="app">
<p><strong>Shopping list:</strong></p>
<ul id="ulToFind">
<li v-for="item in shoppingList"
v-on:click="item.found = !item.found"
v-show="!item.found">
{{ item.name }}, {{ item.number}}
</li>
</ul>
<ul id="ulFound">
<li v-for="item in shoppingList"
v-on:click="item.found = !item.found"
v-show="item.found">
{{ item.name }}, {{ item.number}}
</li>
</ul>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
shoppingList: [
{ name: 'Tomatoes', number: 5, found: false }
]
}
}
})
app.mount('#app')
</script>

Anandu G NathPosted Jan 26, 2024, 3:32 AM
Nice article