'Vuejs highlight color on a clicked item in a list of items?

How can we highlight a item in a list of item when the particular item is clicked? Should we use id as reference?

<li v-for="todo in todos">
  <label>
    <a href="#"
      v-on:click="toggle(todo)"
      :style="{color:activeColor}"
      >


      {{ todo.text }}

    </a>

  </label>
</li>
toggle: function(todo){

  this.activeColor = 'red'
}

I tried here: https://jsfiddle.net/eywraw8t/110976/



Solution 1:[1]

You can add activeIndex to store current active index:

<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="(todo, idx) in todos">
      <label>
        <a href="#"
          v-on:click="toggle(idx)"
          v-bind:checked="todo.done"
          :class="{'active': idx == activeIndex}"
          >
          {{ todo.text }}

        </a>

      </label>
    </li>
  </ol>
</div>

new Vue({
  el: "#app",
  data: {
    activeColor:String,
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: false },
      { text: "Build something awesome", done: false }
    ],
    activeIndex: null
  },
  methods: {
    toggle: function(index){
        this.activeIndex = index
    }
  }

and in css

.active {
  color: red;
}

Demo: https://jsfiddle.net/Lv7eanru/

Solution 2:[2]

This is another solution to highlight selected item in a list using VueJS :

<div id="app">
<ul>
    <li v-for="value in objectArray"  v-on:click="highlight($event)" >
          First name : {{ value.firstName }}  -- Last name : {{ value.lastName }}
    </li>
</ul>

and in JS file we have:

Vue.createApp({
data() {
    return {            
        objectArray: [{
            firstName: 'John',
            lastName: 'Doe'
        },
        {
            firstName: 'Amily',
            lastName: 'Brown'
        },
        {
            firstName: 'Jack',
            lastName: 'London'
        },
        ],
    }
},
methods: {
    highlight: function (event) {
        for (var i = 0; i < event.target.parentElement.children.length; i++) {
            event.target.parentElement.children[i].classList.remove('bg-warning');
        }
        event.target.classList.add('bg-warning');                     
    }
},
}).mount('#app');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ittus
Solution 2 ehsan_kabiri_33