Binding Classes

Follow along with this video on CodePen

When using the v-bind directive with the class attribute, it is possible to use an Object or an Array syntax instead of simply manipulated a string.

Object Syntax

The object syntax allows for classes to be added based on the truthiness of the provided expression. The class (the object key) will added if the expression (the object value) evaluates to true.

<a href="#" v-bind:class="{ active: isActive }">About</a>

In the example above, the class active will be added to the element if the isActive a data property of the Vue instance is truthy.

You can toggle more classes by adding additional properties to the object.

::: NOTE If the class name as a dash (-) it will need to be placed in quotes. :::

<a href="#" v-bind:class="{ active: isActive, 'link-home': isHome }">About</a>

A full example, might look something like this:

<div id="app">
  <nav class="nav">
    <a v-for="link in links" href="#" class="nav-link" v-bind:class="{ active: link.isActive, 'home': link.isHome }">{{ link.title }}</a>
  </nav>
</div>
const app = new Vue({
  el: '#app',
  data: {
    links: [
      { title: 'Home', isActive: false, isHome: true},
      { title: 'About', isActive: true, isHome: false}
    ]
  }
})

Array Syntax

An array can be used to apply a list of classes from data properties to an element.

<div v-bind:class="[activeClass, errorClass]"></div>
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

The data property will replaced with there values and will be render as the following:

<div class="active text-danger"></div>

Using the array syntax can be an effective way of added multiple classes to an element render in a list, as in the following example.

<div id="app">
  <div class="buttons">
    <button 
       v-for="button in buttons" 
       class="btn" 
       v-bind:class="[button.sizeClass, button.colorClass]"
          >{{ button.text }}</button>
  </div>
</div>
const app = new Vue({
  el: '#app',
  data: {
    buttons: [
      { text: "Large Button", sizeClass: 'btn-lg', colorClass: 'btn-primary' },
      { text: "Small Button", sizeClass: 'btn-sm', colorClass: 'btn-danger' },
      { text: "Normal Button", sizeClass: '', colorClass: 'btn-secondary' },
    ]
  }
})