In Vue.js, data binding refers to a mechanism that links data sources (typically component data objects) to UI elements such as input fields and text. This enables the UI to automatically update in response to changes in the data source, and vice versa. Vue.js achieves data binding primarily through a declarative programming approach, allowing developers to focus on managing data states without manually handling the DOM.
Vue offers several different data binding approaches:
-
Interpolation Expressions (Mustache): This is the most fundamental data binding method, used to display the result of JavaScript expressions within double curly braces
{{ variable }}. For instance, define anamevariable in the component's data and use{{ name }}in the template to show its value.html<template> <div> Hello, {{ name }}! </div> </template> <script> export default { data() { return { name: 'Vue' } } } </script> -
v-bind Directive: This directive binds HTML attributes to expressions, such as binding the
srcattribute of an<img>element to theurlvariable in the component's data.html<template> <img v-bind:src="imageUrl"> </template> <script> export default { data() { return { imageUrl: 'path/to/image.jpg' } } } </script> -
v-model Directive: This directive enables two-way binding between form inputs and application state. For example, binding the
valueof an<input>element to thevaluevariable in the component's data ensures that changes in either are reflected in the other.html<template> <input v-model="message"> </template> <script> export default { data() { return { message: '' } } } </script>
By utilizing these data binding methods, Vue enables developers to minimize direct DOM manipulation, streamline the synchronization between data and views, and enhance development efficiency and application performance.