Vue.js toggle class on click

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.


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
    }
  }
})

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
}

If you don't need to access the toggle from outside the element, this code works without a data variable:

<a @click="e => e.target.classList.toggle('active')"></a>