How to toggle a class on click in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to toggle a single class or multiple classes in Vue.js. If you’re new to Vue.js learn how to bind HTML classes first.

Let’s start by writing an HTML part of the component:

<div id="app">
  <a href="#" :class="{ active: isActive }" @click="isActive = !isActive">Click me</a>
</div>

Vue.js

new Vue({
  el: "#app",
  data: {
    isActive: false
  },
  methods: {}
})

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

.active {
  background: #f00;
  color: #fff;
  font-size: 30px;
}

In the example above, we have an isActive boolean in a data() object. It’s set to false. There’s a click event on a link element, which toggles isActive value on every click.

<a href="#" :class="{ active: isActive }" @click="isActive = !isActive">Click me</a>

Link class depends on an isActive value. If it’s set to true, the class active will be set dynamically.


Hi, I'm Renat 👋

 


You can set multiple classes, see the example below.

<div id="app">
  <div :class="{ 'active': isActive, 'loading': isLoading }"></div>
</div>

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-toggle-class

PS: Make sure you check other Vue.js tutorials, e.g. how to pass a parameter to a method in Vue.js.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

4 Comments

  1. I love how your explanation was straight to the point! Great work. Looking forward to checking out more of your tutorials.

    I’m struggling a bit to find a solution because I am trying to change the class to just 1 of many list items and this solution is changing the class for all of them.