Conditional Classes in Vue.js

Vue.js v-bind supports dynamic binding of classes using 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 bind multiple classes together conditionally and use v-bind shorthand which is :


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;


In string syntax the value that needs to be bound to a class using v-bind can be a string and not an object. 


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';


You can bind a class to an array. Vue will bring together all elements in the array to produce the final class binding result. 


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;