How do you 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.
How do you do this in vue.js?
This answer relevant for
Vue.js version 2
The rest of the answer by Douglas is still applicable (setting up the new Vue instance with
isActive: false
, etc).Relevant docs: https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax and https://vuejs.org/v2/guide/events.html#Method-Event-Handlers
This example is using Lists: When clicking in some li it turn red
html:
JS:
css
Fiddle:
https://jsfiddle.net/w37vLL68/158/
You could have the active class be dependent upon a boolean data value:
If you need more than 1 class
You can do this:
Notice the single quotes ' around the classes!
Thanks to everyone else's solutions.
Without the need of a method:
I've got a solution that allows you to check for different values of a prop and thus different
<th>
elements will become active/inactive. Using vue 2 syntax.