Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 841
cooler Avatar asked Jun 26 '18 05:06

cooler


1 Answers

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/

like image 175
ittus Avatar answered Sep 29 '22 12:09

ittus