Conditional Classes in Vue

Jan 6, 2020

Vue's v-bind syntax supports dynamically binding classes via an object syntax.

const app = new Vue({
  data: () => ({ isGreen: true }),
  // `div` will have class 'green' if `isGreen` is true
  template: `
    <div v-bind:class="{ green: isGreen }"></div>
  `
});

// Remove the class 'green' from the `div`
app.$data.isGreen = false;

You can conditionally bind multiple classes, and use the : shorthand for v-bind::

const app = new Vue({
  data: () => ({ green: true, small: false }),
  // `div` will have class 'green' if `green` is true
  // and 'small' if `small` is true.
  template: `
    <div :class="{ green, small }"></div>
  `
});

// Remove the class 'green' from the `div` and add class 'small'
app.$data.green = false;
app.$data.small = true;

String Syntax

The value you bind to class with v-bind can be a string, not just an object. For example, you can store the class name in a data string:

const app = new Vue({
  data: () => ({ myClass: 'green' }),
  // `div` will have whatever class or classes are in the
  // `myClass` data value.
  template: `
    <div :class="myClass"></div>
  `
});

// Remove the class 'green' from the `div` and replace it
// with the class 'small'
app.$data.myClass = 'small';

Another neat approach is to use the ternary operator to decide which class the element will have:

const app = new Vue({
  data: () => ({ isGreen: true }),
  // `div` will have class 'green' if `isGreen` is true.
  template: `
    <div :class="isGreen ? 'green' : 'small'"></div>
  `
});

// Remove the class 'green' from the `div` and replace it
// with the class 'small'
app.$data.isGreen = false;

Array Syntax

You can also bind the class to an array. Vue will then combine all elements in the array to form the final class binding. This lets you mix and match string and object syntax in one declaration:

const app = new Vue({
  data: () => ({ green: true }),
  // `div` will have class 'green' if `green` is true, and
  // 'small' otherwise.
  template: `
    <div :class="[{ green }, green ? '' : 'small']"></div>
  `
});

// Remove the class 'green' from the `div` and replace it
// with the class 'small'
app.$data.green = false;

More Vue Tutorials