Computer scienceFrontendVue.jsVue 3 SyntaxVue Directives

v-bind

7 minutes read

The v-bind directive comes in handy when you need to connect dynamic values to HTML attributes, such as src, href, input's value, and others. It allows us to synchronize state variables with HTML attributes so we can create more dynamic and interactive apps. Let's find out how v-bind works, see its use cases, and understand why we can't use interpolation instead.

What is v-bind?

v-bind is a directive in Vue.js that allows developers to bind data to elements in the view. This means that changes to the data will automatically update the view, and vice versa: changes to the view will update the data.

The syntax of v-bind is simple. It starts with the prefix v-bind: followed by the attribute that you want to bind. For example, if you want to bind the src attribute of an image element, you would use v-bind:src like this:

// src/App.vue

<script setup>
import { ref } from 'vue';

const imgLink = ref('https://images.unsplash.com/flagged/photo-1557427161-4701a0fa2f42?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=387&q=80');

</script>

<template>
  <h1>Marco</h1>
  <img v-bind:src="imgLink" />
</template>

In this example, you have a link stored inside the imgLink constant, and you've bound it with the src attribute in the template. Now, whenever you need to change the link, you'll just change it in the script tags, and the template will adjust automatically. By the way, you can also use the shorthand syntax :src="imgLink":

<template>
  <h1>Marco</h1>
  <img :src="imgLink" />
</template>

You may ask, why not just use the interpolation (double curly braces) instead of the directives? Well, this approach doesn't work with attributes because Vue treats them as regular strings. Try to change your code to this, and you'll see it won't work:

<img src={{imgLink}} />

And the browser's code inspector also shows that it isn't a link:

<img src="{{imgLink}}"></img>

That's why learning v-bind and understanding its use is super important. Now that you've been introduced to v-bind, let's see some other use cases.

V-bind with HTML tags

In this section, we'll go over a couple of examples where v-bind can be used. Suppose you receive an object with some user data from the backend. Each user has their name, picture, and a social media link. We need to render this data dynamically, so that if the user decides to change their info at some point in the future, we still have the updated version.

Inside the script tags, declare three values: name, img, social. You may use any name, but for the picture and social, you'll need to use links. This is how it should look like:

// src/App.vue

<script setup>
import { ref } from 'vue';

const name = ref('Ian Dooley');
const img = ref('https://images.unsplash.com/photo-1499126506967-b33161b9cc83?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=870&q=80');
const social = ref('https://instagram.com');

</script>

Next, let's render these inside the template. The src, value and href attributes should be used with v-bind because we want them to depend on our state:

// src/App.vue

<template>
 <div class="user">
    <img v-bind:src="img" />
    <input v-bind:value="name" />
    <a v-bind:href="social">Socials</a>
 </div>
</template>

Add a bit of CSS magic to make the page look prettier:

// src/App.vue

<style>
 .user {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 1rem;
 }

 img {
  width: 600px;
  height: 400px;
  border-radius: 10px;
 }
 input, a {
  font-size: 2rem;
  text-align: center;
 }
</style>

Here's the result:

user-page

Did you notice that we used input for the name? There are two reasons for this. Number one is, we want to let the user modify the name if they wish to. Secondly, it's a good way to see more examples with v-bind.

V-bind with classes

Another common thing you'll encounter when building apps is dynamic styles. In other words, you'll need to change the styles depending on user behavior. For example, you'd want to change the color of the input if it has an error, change the theme of the app from light to dark, and many other cases.

Let's say you have a div element. You want it to be red if it's active and green if it's not. In other words, you want to apply a new CSS class if a boolean is set to true, and toggle classes based on the true or false value of the boolean. Create an isActive constant and set it to false to begin with. In the template, we'll need a simple div and a v-bind directive to connect the class with the state variable:

// src/App.vue

<script setup>
import { ref } from 'vue';

const isActive = ref(false);

</script>

<template>
  <div v-bind:class="{active: isActive}">Hi, I'm a simple div</div>
</template>


<style>
div {
  width: 200px;
  text-align: center;
  background-color: darkcyan;
  color: white;
}
.active {
  background-color:red
}
</style>

The class attribute accepts an object where we can list all the classes we need. In our case, we have only one class — active — it will be toggled on if isActive property is true. In the style tag, we first specified a default look for the div with dark cyan background color and the active class with red color.

If you open your page in the browser, you will see this:

green div

Let's now set the isActive variable to true to see what will change. The result will look like this:

red div

Cool, we were able to link and toggle classes! By the way, as we mentioned, you can specify as many classes as you want and include them all inside the object that will be passed to the class attribute. Let's see this in action.

Add a new state property below isActive, call it isVerdana, and set it to false:

// src/App.vue

<script setup>
import { ref } from 'vue';

const isActive = ref(true);
const isVerdana = ref(false);

</script>

Create a new class inside the style tag:

.verdana {
 font-family: Verdana, Geneva, Tahoma, sans-serif;
}

Finally, in your template, you can list the styles as follows:

// src/App.vue

<template>
  <div :class="{active: isActive, verdana: isVerdana}">Hi, I'm a simple div</div>
</template>

Feel free to play around with it, switching the isVerdana state between true and false to see how it affects the view.

It's also possible to use array syntax when listing class names. This might be useful if you have many classes, some of which depend on the state, whereas others don't. For example, if you want to keep the logic for the active class and also add a default class that isn't tied to the state, you can write something like this. The yellow class will be independent of the state, while the active class will be dynamic:

// src/App.vue

<script setup>
import { ref } from 'vue';

const isActive = ref(false);

</script>

<template>
  <div v-bind:class="[{ active: isActive }, 'yellow']">Hi, I'm a simple div</div>
</template>


<style>
div {
  width: 200px;
  text-align: center;
  background-color: darkcyan;
  color: white;
}
.active {
  background-color:red
}

.yellow {
  color: yellow;
}
</style>

Let's see the output.

If isActive is false:

2-classes green div

If isActive is true:

2-classes red div

As you can see, the font color is always yellow, while the background changes dynamically.

Feel free to check out Vue Docs for more info on class binding.

Conclusion

The v-bind directive allows you to bind the state to HTML attributes. It provides a simple and efficient way to create dynamic and reactive user interfaces. In this topic, we covered the basics of v-bind, including its syntax, shorthand syntax, and use cases. You now know how to sync the HTML attributes to the state and work with classes.

4 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo