How to Toggle CSS Class in Vue.js

Published on September 30, 2020 29 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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

Author

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

Follow

Leave a Reply

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