How to toggle class on click with Vue.js?

Sometimes, we want to toggle class on click with Vue.js.

In this article, we’ll look at how to toggle class on click with Vue.js.

How to toggle class on click with Vue.js?

To toggle class on click with Vue.js, we can set the class prop to an image with the class name as the property name and the condition to enable the class as the value.

For instance, we write

<template>
  <div
    :class="{ active: showMobileMenu }"
    @click="showMobileMenu = !showMobileMenu"
  >
    click me
  </div>
</template>

to set the active property to showMobileMenu to apply the active class if showMobileMenu is true.

And we set @click to showMobileMenu to its negation to toggle showMobileMenu.

As a result, when we click on the div, the active class would be toggled on and off.

Conclusion

To toggle class on click with Vue.js, we can set the class prop to an image with the class name as the property name and the condition to enable the class as the value.