Skip to content
Advertisement

What is the simplest way to toggle a class on/off of an element without affecting other elements using Vue.js?

I have seen several examples of how to toggle a class in Vue.js like this:

JavaScript
JavaScript
JavaScript

Clicking the element toggles if it is active true or false and you are then toggling the class. This is fine, but doesn’t work when you have more elements that you also what to toggle and active class on and off like this:

JavaScript
JavaScript
JavaScript

Now we are toggling the same for all of them, even though we just want to toggle the individual element that was clicked.

I know in jQuery this would be very simple:

JavaScript
JavaScript
JavaScript

I have seen an example that required an entire component to be made that needed to be exported/imported just to scope the isActive property to that individual div, however that solution seems like a lot for such simple behavior. So what would be the simplest solution to toggling an .active class on/off of individual elements like my jQuery example?

Advertisement

Answer

You can do that with java script like that:

JavaScript
JavaScript
JavaScript

Or as you mentioned you can create a component like that:

JavaScript

html:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement