5

When I toggle my variable active in the code below, the active CSS class is applied/removed from all elements in the list. How do I target the list elements individually? The Todo-List example has similar functionality (with todo / todo completed), but it's a bit beyond my skill set.

<ul>
    <li v-bind:class="{ active: active }" v-on:click="toggleActive">Test 1</li>
    <li v-bind:class="{ active: active }" v-on:click="toggleActive">Test 2</li>
    <li v-bind:class="{ active: active }" v-on:click="toggleActive">Test 3</li>
</ul>

toggleActive: function() {
    this.active = !this.active;
}
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Pyreal
  • 517
  • 3
  • 8
  • 19
  • 1
    We'd need more details than this to provide the best answer. What makes something "active"? – Bill Criswell Nov 21 '16 at 21:45
  • to keep the example simple, let's say that it was clicking on the text, I've updated my example to reflect this. – Pyreal Nov 21 '16 at 21:53
  • 1
    Since there's no way to really calculate with data what's "active" you might need to use pure DOM manipulation. If those links were in a loop you'd be able to tie active state to the index of the element at least. You might actually want a little more to make this example simple. – Bill Criswell Nov 21 '16 at 21:56
  • 1
    If you were to make each `
  • ` it's own component it can have it's own `active` property and you can change that at the component level.
  • – Bill Criswell Nov 21 '16 at 22:01
  • I am using a v-for in my code to create my list of
  • elements, are you saying you can attach an id to each
  • element with the loop?
  • – Pyreal Nov 21 '16 at 22:04
  • No. `:key` is a different thing. You can do like `v-for="(item, index) in items"` then `:class="{ active: selected === index }"` then in `toggleActive(index)` set `this.selected = index`. – Bill Criswell Nov 21 '16 at 22:06
  • 1
    `selected` wouldn't need to be an `index`, it could be anything on item that's unique to it if you wanted to, so like `toggleActive(item.id)`. – Bill Criswell Nov 21 '16 at 22:06
  • alright, I'll see if I can apply this to my code. thanks for the input. – Pyreal Nov 21 '16 at 22:08
  • 2
    My answer here is *very* similar to your situation: http://stackoverflow.com/questions/39778665/vue-js-v-show-in-a-list/39779332#39779332 – Bill Criswell Nov 21 '16 at 22:10
  • 1
    See also my answer here: http://stackoverflow.com/a/40663349/1165998 – David L Nov 21 '16 at 22:15
  • 2
    Haha. Very similar as well. – Bill Criswell Nov 22 '16 at 00:17