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.
We can toggle a class dynamically in vue by passing an object to the v-bind:class attribute. In this example, we are toggling a class by clicking the Toggle button.
Toggle The Active CSS Class Based on the isActive property, let's toggle active class in the button element by adding an object to the :class. The active class, which is the key of the object, will get added to the button when isActive is set to true which is the value of the object. Nice.
Create a ToggleButton.vue file. Next, add some HTML such as On / Off and a checkbox input field. Don't confuse with the both On and Off text, we will handle it to the next section. The next step is to add a default state that will handle the toggle button On / Off text.
Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.
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 } } })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With