Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js toggle class on click

Tags:

css

vue.js

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.

like image 662
adam78 Avatar asked Nov 16 '15 09:11

adam78


People also ask

How do I toggle a class at Vue?

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.

How do I use Vue toggle in JavaScript?

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.

How do you make a toggle button on the Vue?

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.

How do I add dynamic classes to Vue?

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.


1 Answers

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     }   } }) 
like image 171
Douglas.Sesar Avatar answered Oct 14 '22 01:10

Douglas.Sesar