Add class on clicked list element, remove class from not clicked elements

Hi, I’d like to add a class ‘active’ to the selected li element, but remove it from the li elements not selected. What is the vue.js way to achieve that? (In my example I won’t use a v-for list).

<div id="app">
 <ul class="list">
   <li class="list-item" v-on:click="isActive = !isActive" v-bind:class="{ active: isActive }"> 
     Element 1
  </li>
  <li class="list-item" v-on:click="isActive = !isActive" v-bind:class="{ active: isActive }"> 
     Element 2
  </li>
  <li class="list-item" v-on:click="isActive = !isActive" v-bind:class="{ active: isActive }"> 
     Element 3
  </li>
 </ul>
</div>

And in my js file:

 new Vue ({
 el: '#app',
 data: {
    isActive: false
 });
1 Like

Here are some examples I prepared earlier: https://jsfiddle.net/Herteby/todqxteh/

6 Likes

Thanks Herteby for your super quick reply. I have to add that I won’t use a v-for list in my example (the content will be generated with a liquid loop).

It could work without v-for too. If the items have a unique ID you could use that, or you could use the item object itself. But the general approach is to have a variable on the parent component that you set and compare with. What’s a liquid loop btw?

2 Likes

Thanks Herteby.

Do you have an example for setting a variable on the parent component?

Also is the approach of having a v-on:click and v-bind:class on each element as written down in my first post correct?

I’m bit confused what I have to achieve with javascript functions in the Vue instance and what can be done with Vue.js.

(It’s for a jekyll site in which I use the Liquid templating system (https://jekyllrb.com/docs/datafiles/)).

Here’s an example without using v-for:
https://jsfiddle.net/Herteby/5amw1mfn/
Seems a bit awkward to generate HTML with another framework instead of with Vue, but it could work I guess.

8 Likes

Wow, that’s straightforward - thanks loads. Very appreciated.

1 Like

Thank for awesome solution

1 Like

Your solution really help me so much. Thank you.