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 attributes to HTML is very easy. In vuejs, we have v-bind directive, which is very powerful and it 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 it's 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" />

To add dynamic class or style property to your div. You can do it using v-bind, as it helps in class and style Bindings too.

V-bind a dynamic class attribute in HTML

You can bind more then 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 add active and text-danger class 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 the 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 example how you can add class, style and a image src attribute dynamically in your HTML code using VueJS. There are lot more, which you can read on their VueJS Binding Documentation.

Related Topics:

How to add common header and footer in vuejs.


💾 Recommended Articles