Attribute binding in Vue.js

Author
By Darío Rivera
Posted On in Vue.js

In our previous post we saw how to create our First Vue.js application and demonstrated why it is a reactive framework. Today we will see how attribute binding is done in Vuejs to link HTML element attributes.

What is attribute binding?

Attribute binding is a Vue feature that allows binding HTML element attributes with the value of a property.

attribute binding in Vue

Image taken from Vue Mastery

For instance, it allows binding the source value of an image (src) with a property defined in the context where the image is located.

How does attribute binding work?

Let's say we have the following HTML.

<div id="app">
  <img src="https://blog.pleets.org/img/articles/vuejs-icon.png" width="80" /> {{ '\{\{ $message \}\}' }}
</div>

And, for this, the following JavaScript with the Vue instance.

var app = new Vue({
  el: '#app',
  data: {
    message: 'Vue.js'
  }
});

The way to dynamically generate the image, or rather, link it from Vue data is not like printing a common message with interpolation as is the case of the message variable. For this, Vue provides us with the v-bind directive. The syntax for this would be as follows:

v-bind:attribute="property"

Where attribute is the attribute of the HTML element and property is the property in Vue.js. According to this, the way to link the src attribute of the image with Vue would be as follows.

<div id="app">
  <img v-bind:src="image" width="80" /> {{ '\{\{ $message \}\}' }}
</div>
var app = new Vue({
  el: '#app',
  data: {
    message: 'Vue.js',
    image: 'https://blog.pleets.org/img/articles/vuejs-icon.png'
  }
});

At this point, generalizing the syntax would actually allow not only placing the value of a property in the context but an entire expression.

v-bind:attribute="expression"

Finally, Vue.js makes our life a little easier by adding a shorthand for this directive as follows.

:attribute="expression"

See you soon!


Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.