Vue.js toggle class on click

adam78 picture adam78 · Nov 16, 2015 · Viewed 212.9k times · Source

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

Answer

moabi picture moabi · May 8, 2017

Without the need of a method:

// html element
<div id="mobile-toggle"
 v-bind:class="{ active: showMobileMenu }"
 v-on:click="showMobileMenu = !showMobileMenu">
</div>

//in your vue.js app
data: {
    showMobileMenu: false
}