18. Class bindings

Welcome to yet another binding discussion. Today, I will be schooling you on class bindings. In other words, we will be playing around with HTML element’s class attribute by binding data to it using Vue. Why? Because we might be required to often manipulate the class list of an element. Just like any other data binding, we do the same song and dance here as well, i.e. the mighty “v-bind” or its shortcut “: “can be used to handle this scenario. Expressions can be evaluated to strings, objects or arrays.

Sounds confusing? No worries! Let’s take one step at a time with the backing of some examples. You will see yourself sprinting in no time!

Initial code:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Vue!</title>
    <!-- including Vue with development version CDN -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <h2>Welcome</h2>
      <div> 
        <!-- OUR CODE GOES HERE -->
      </div>
    </div>
    <!-- including index.js file -->
    <script src="index.js"></script>
    <link rel="stylesheet" href="style.css"></link>
  </body>
</html>

index.js

new Vue({
  el: "#app",
  data: {}
});

style.css

<!-- LET US WRITE SOME CODE AS WE GO -->

Object Syntax

Let’s say we have a class named “success” and its styles are defined in style.css stylesheet as follows,

.success {
  color: green;
  font-weight: bold;
  font-size: 70px;
}

With Vue, it is very easy to dynamically toggle this class by passing it as an object to v-bind:class.

index.html (snippet)

<div id="app">
  <h2>Welcome</h2>
  <div> 
  <!-- class bindings: Objects -->
  <div :class="{ success : successFlag }">
    Hello!!
  </div>
    <p>The value of successFlag is {{ successFlag }}</p>
  </div>
</div>

The shortcut : is used for the directive v-bind here.

index.js

new Vue({
  el: "#app",
  data: {
    successFlag : true
  }
});

Very simple! We have a div tag which displays, “Hello!!”. Since the data property, successFlag value is true, the class success is included in the div tag and its styles are applied to the text within the tag.

class binding with objects

The result can be clearly seen in the browser. Chrome DevTools pane shows how the ‘success’ class is present in the HTML code.

In case we set the value of successFlag to false, then this is how the output will look.

index.js (snippet)

data: {
  successFlag : false
}

Toggle class

Works like a charm!

WHAT IF we have the plain class attribute and on top of it, we would like to toggle the presence of another class with the help of v-bind:class? In other words, can we have class and v-bind:class at the same time on an element? Is it possible?

YESSSS!! With Vue, almost everything is a yes!

The best part is, we can achieve this in two ways.

Method 1: Inline object

index.html (snippet)

<div> 
  <!-- class bindings: Objects -->
  <div class="underline" :class="{ success : successFlag, bcg : bcgFlag }">
    Hello!!
  </div>
  <p>The value of successFlag is {{ successFlag }}</p>
</div >

index.js (snippet)

data: {
  successFlag: false,
  bcgFlag: true
}

style.css (snippet)

.underline {
  text-decoration-color: red;
  text-decoration-line: underline;
}
.bcg {
  background-color: aqua;
  padding: 5px;
  width: fit-content;
}

The plain class attribute has the class, underline which will always be rendered.

It is also possible to have more fields in the object passed to v-bind:class. To understand this, let us toggle two classes based on the truthiness of its values. In the above code, two classes success and bcg are passed as an object to v-bind:class. successFlag and bcgFlag are set to false and true respectively. So, the class list that is rendered becomes, “underline bcg” and only those styles are applied.

Method 2: Bound object not inline

index.html (snippet)

<div class="underline" :class="classObject">
  Hello!!
</div>

index.js (snippet)

data: {
  classObject: { 
    success : false, 
    bcg : true 
  }
}

The object to be bound to v-bind:class is specified in vue instance’s data.

binding multiple objects

Array Syntax

Instead of using objects, classes can be passed in the form of an array to v-bind:class like so,

index.html (snippet)

<!-- class bindings: Arrays -->
<div class="underline" :class="[successClass, bcgClass]">
  Array Bindings.
</div>

index.js (snippet)

data: {
  successFlag: false,
  bcgFlag: true,
  successClass: 'success',
  bcgClass: 'bcg'
}

For simplicity, I am using the same classes for this example too.

This will render all three classes when inspected in chrome DevTools,

<div class="underline success bcg">

Class binding with arrays

All the code discussed above is available in the GitHub repo

Fire up your favorite IDE and code a few scenarios of your own! If you have any questions, feel free to shoot them in the comments section. Stay tuned as our next post is all about binding inline styles.

 

<< 14. Two-way data binding with v-model

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.