Dynamic Class Binding with VueJS

Let’s now learn how to dynamically bind and change classes in HTML elements using VueJS.

Problem: You want to dynamically change the class name of an HTML element depending on VueJS data property.

Solution:

There are two ways you can achieve this, let’s review both of them.

#1 Using Object Syntax

Let’s work with a simple HTML element that changes its color depending upon the data property value of the VueJS Instance.

We initialize a new VueJS instance with a single data property.

    var app = new Vue({
        el: '#app',
        data: {
            isActive : true
        }
    });

Our goal is to attach a class active to the h3 element if the value of data property isActive is true.

Here is the CSS for active class, add this inside head element of your HTML page.

    <style>
        .active{
            color: green;
        }
    </style>

And here is how we bind the value of data property to the element using object syntax.

    <div id="app">
        <h3 v-bind:class="{active : isActive}">This is a sample text</h3>
    </div>

Notice that we have used a new directive named v-bind before the class attribute, which basically evaluates the value in of the data property in the object and if it evaluates to be true it assigns the value to the class attribute. In this case, if isActive is true active class will be applied to the class attribute.

Try changing the value of isActive to false from the console or using the VueJS Dev Tools, you should see the color of text change from green to black (default color without the class).

#2 Using Array Syntax

You can use Array Syntax to dynamically apply the class and also you can use it to toggle the classes.

Let’s add another class named notActive in our CSS Rules.

        .notActive{
            color: red;
        }

Now, in this scenario we want to display the text as green is the data property isActive is true, otherwise, we will show the text in red.

Here is how you can use the array syntax to dynamically bind and toggle the class.

<h3 v-bind:class="[isActive ? 'active' : 'notActive']">This is a sample text</h3>

Try changing the value of property isActive from developer console or using the VueJS Dev Tools, and see text toggling between green and red and it dynamically switches the class that is attached to it.

Practice Excercises

  1. Using dynamic binding to disable the button on clicking it. (CodePen Solution Link)
  2. Place three buttons red , green and blue in a div and change the background color of the div as per the button clicked . (CodePen Solution Link)

Join my VueJS Newsletter

As I advance in my Journey of learning VueJS, I will be working on different exercises and challenges. Subscribe to receive the latest tutorials (every week) directly in your inbox.

    I won't send you spam. Unsubscribe at any time.

    Powered By ConvertKit

    Leave a reply:

    Your email address will not be published.

    Site Footer