98

How does toggle a class in vue.js?

I have the following:

<th class="initial " v-on="click: myFilter">
    <span class="wkday">M</span>
</th>

new Vue({
  el: '#my-container',
  data: {},
  methods: {
    myFilter: function(){
      // some code to filter users
    }
  }
});

When I click <th> tag I want to apply active as a class as follows:

<th class="initial active" v-on="click: myFilter">
    <span class="wkday">M</span>
</th>      

This needs to toggle i.e. each time its clicked it needs to add/remove the class.

Penny Liu
  • 11,885
  • 5
  • 66
  • 81
adam78
  • 8,930
  • 20
  • 79
  • 187

12 Answers12

105

You could have the active class be dependent upon a boolean data value:

<th 
  class="initial " 
  v-on="click: myFilter"
  v-class="{active: isActive}">
  <span class="wkday">M</span>
</th>

new Vue({
  el: '#my-container',

  data: {
    isActive: false
  },

  methods: {
    myFilter: function() {
      this.isActive = !this.isActive;
      // some code to filter users
    }
  }
})
vsync
  • 103,437
  • 51
  • 275
  • 359
Douglas.Sesar
  • 3,874
  • 3
  • 27
  • 36
  • 45
    for some reason `v-class="active: isActive"` crashes my app, but `v-bind:class="{ active: isActive }" ` works for me. Hope this is helpful for someone. – Frazer Kirkman Jan 21 '17 at 17:35
  • My example is from version 0.12 – Douglas.Sesar Jan 23 '17 at 01:37
  • 7
    syntax seems to change all the time with vue. In 2.* you can also just do `:class="..."` – rzb Feb 25 '17 at 07:39
  • 7
    I am doing it in vue.js-2. When I click on one row, the `active` class is being applied to all the rows. Am I doing something wrong? – Syed Apr 18 '17 at 14:00
  • 1
    you can make each row its own component that is responsible for its own `isActive` property – Douglas.Sesar Apr 20 '17 at 19:32
  • 3
    all of the examples for setting an Active class are for just one item, what if I had multiple I v-for rendered, how then would I impart Active class on the most recently clicked of this list. `{{ room.name }} ` – Akin Hwan Feb 20 '18 at 15:44
  • looks like I can't use double hyphen in my class name with this method? for example `:class="{ click--butonClass: ifTrue }"` – Akin Hwan Mar 30 '18 at 15:15
  • 1
    If the class name has a hyphen => `v-bind:class="{ 'active-class': isActive }"` – aero Jun 21 '18 at 22:04
99

Without the need of a method:

// html element, will display'active' class if showMobile is true
//clicking on the elment will toggle showMobileMenu to true and false alternatively
<div id="mobile-toggle"
 :class="{ active: showMobileMenu }"
 @click="showMobileMenu = !showMobileMenu">
</div>

//in your vue.js app
data: {
    showMobileMenu: false
}
moabi
  • 1,291
  • 9
  • 9
  • And what is active? `showMobileMenu` is a variable but what is the class? – rjurney Apr 29 '20 at 16:39
  • @rjurney `active` is the CSS class. Better written this way: `'active': showMobileMenu`, but it's the same thing. – Laurensius Adi Jan 13 '22 at 13:35