How to add dynamic HTML attributes in VueJS ?

In this article, we will learn How to add dynamic attributes in VueJS.

In vue, adding a dynamic attribute to HTML is very easy. In vuejs, we have v-bind directive, which is very powerful and can provides us with attribute binding capabilities.

What does v-bind do in Vuejs?

The v-bind directive is used to bind one or more attributes in our HTML template. It also helps to bind a component prop to an element too.

You can use v-bind with its shorthand version : .

Using v-bind you can bind class, style, id, src, and even href in your HTML.

Add dynamic src attribute in HTML using v-bind

To add dynamic src attribute in your<img /> tag in HTML, you can just bind it as:

<img v-bind:src="imgSrc" />
//OR
<img :src="imgSrc" />

If you want to add a dynamic class or style property to your div, you can do it using v-bind.

V-bind a dynamic class attribute in HTML

You can bind more than one class in your HTML template.

<div
  class="static"
  v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>

<script>
export default {
  name: "App",
  data() {
    return {
      isActive: true,
      hasError: false
    };
  },
};
</script>

Here in the example, we have added active and text-danger classes dynamically using v-bind.

When isActive or hasError changes, the dynamic classes will be added accordingly.

Add dynamic inline styles in HTML

The object syntax of v-bind:style helps us to add CSS to our template, except it’s a JavaScript object.

Use camelCase for the style property names.

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
<script>
export default {
  name: "App",
  data() {
    return {
      activeColor: 'red',
      fontSize: 30
    };
  },
};
</script>

Add dynamic class as Object in Vuejs

You can also use v-bind to add Object to HTML template.

<div v-bind:class="classObject"></div>

<script>
export default {
  name: "App",
  data() {
    return {
     classObject: {
        active: true,
        'text-danger': false
      }
    };
  },
};
</script>

These are some of the few examples of how you can add class, style, and an image src attribute dynamically in your HTML code using VueJS. There are a lot more, which you can read on their VueJS Binding Documentation.

Related Topics:

How to add common header and footer in vuejs.

How To Add Multiple Classes In VueJS ?

Call a Vue.js Component Method From Outside The Component

Scroll to Top