3. Using v-model for Two-Way Binding and Dynamic Style and Class in Vue.js
Two-Way Binding
Two-way binding is a powerful feature that, if used properly, can speed up your development process. It reduces the complexity of keeping user input consistent with the application data model.
Do check out the video tutorial on Two Way Binding here.
The v-model
directive updates the template whenever the model changes and updates the data model whenever the template changes.
In Vue.js you can handle Two-Way Data binding with v-model
the directive.
Binding to Text Input Elements
To bind the value of an input element to a property of your component’s data, use v-model="dataProperty"
like so.
<div id="app">
<p>Your Name: {{name}}</p>
<input v-model="name" placeholder="Enter Name">
</div><script>
new Vue({
el: "#app",
data:()=>({
name: ''
})
})
</script>
Dynamic Style and Class
With the :style
the directive, you will visualize your font size on a click event. With :class
, you will observe how to apply multiple classes to elements.
Binding Styles Dynamically
<div id="app">
<p :style="{ fontSize: fontSize + 'px' }">{{name}}</p>
</div><script>
new Vue({
el: "#app",
data:()=>({
name:'This is Title',
fontSize: 10
})
})
</script>
Binding Classes Dynamically
You can add a dynamic class in Vue.js with :class
and here is this example if the data value is more than 5 then, redTitle
the class will be added otherwise greenTitle
class.
<style>
.redTitle{
color:red
}
.greenTitle{
color:green
}
</style>
<div id="app">
<p :class="a>5?'redTitle':'greenTitle'">{{name}}</p>
</div><script>
new Vue({
el: "#app",
data:()=>({
a:3
})
})
</script>
Do check out the video tutorial on Two Way Binding here.
You can find more info about Vue Two Way Binding and List Rendering at Vue Documentation.
Keep watching this and follow us for more tech articles or you can reach out to me for any doubt and suggestions and the next blog in the series will be published soon.
Thanks
Happy Coding!