How to bind HTML attributes in Vuejs
In this tutorial, we are going to learn about binding HTML attributes in vuejs.
This is our starting code.
<template>
<div>
<h1>Binding atrributes in {{title}}</h1>
<img src="" />
</div>
</template>
<script>
export default {
data: function() {
return {
title: "Vuejs",
image: "logo.png"
};
}
};
</script>
In the above code, we need to bind the data of our src
attribute to display the image.
Inside the data
we have image:"logo.png"
property, now we need to link our src
attribute to image
property so that we can display the image.
The problem is curly braces {{}}
syntax doesn’t work to bind the data inside the html attributes.
<img src="{{image}}" /> //wrong: doesn't display any image
Attribute binding
To bind the data inside HTML attributes vue.js provides us a v-bind
directive.
syntax usage.
<img v-bind:src="image" /> // user can see image now
Here v-bind
directive binds the element src attribute to a image
expression, so we can see the image.
Shorthand syntax
There is also a shorthand syntax of v-bind:attributename
, which can be also written as just :attributename
.
<!-- fullhand syntax -->
<img v-bind:src="image" />
<!-- shorthand syntax -->
<img :src="image"/>
Similarly, we can use this syntax with other HTML attributes.
<button :disabled="isActive">Click</button>
<a :href="url">My link</a>
<div :class="myClassname"></div>
v-bind directive evaluates the JavaScript expression present inside the quotes
v-bind:src="js expression"
.