How to Toggle CSS Class in Vue.js

Published on September 30, 2020 29 sec read

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. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.

Follow