Categories
Vue Answers

How to add a class conditionally in Vue.js?

Spread the love

Sometimes, we want to add a class conditionally in Vue.js.

In this article, we’ll look at how to add a class conditionally in Vue.js.

How to add a class conditionally in Vue.js?

To add a class conditionally in Vue.js, we can add the :class directive.

For instance, we write

<template>
  <div id="app">
    <div :class="condition ? 'class-if-is-true' : 'else-class'"></div>
  </div>
</template>

to set the class prop of the div to 'class-if-is-true' if condition is true.

Otherwise, we set class to 'else-class'.

Conclusion

To add a class conditionally in Vue.js, we can add the :class directive.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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