How to Toggle CSS Class in Vue.js

In this article, I’m going to show how to toggle CSS class in Vue. Let’s see the example:

Syntax

We can toggle a class in the list conditionally. Here’s the syntax:

<div :class="[isActive ? activeClass : '', anotherClass]"></div>

An Example

Let’s have a look at an example:

<template>
  <div>
    <p :class="[ isRed ? 'text-red' : 'text-light' ]">
      Dummy Text
    </p>
    <button @click="switchColor">Switch</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isRed: false
    }
  },
  methods: {
    switchColor() {
      if(this.isRed)
        this.isRed = false
      else
        this.isRed = true
    }
  }
}
</script>

<!-- styles -->
<style scoped>
  .text-red {
    color: rgb(190, 3, 3);
  }
  .text-light {
    color: rgb(0, 0, 0);
  }
</style>

That’s it. Thanks for reading.