Search code examples
javascriptlistvue.jsdata-bindingtoggle

Vue.js - Toggle clicked icon in v-for generated list


In Vue.js I have generated a list of objects. I would like to color a 'star' when that specific 'star' is click.

But when I click on a star, every star in the list gets colored.

I've made a dummy fiddle here: https://jsfiddle.net/t3f0rpqh/21/

Actually, it's going te be a font-awesome icon (but I have same problem here - on icon change, every icon in the list changes, not just the clicked one).

 <font-awesome-icon
  :class="{ activeIcon: activeIcon}"
  :icon="icon"
  v-on:click="starLocation(item.id)"
 />

I don't know how to bind the star/icon to a specific object or how to color only the clicked star/icon.

Any ideas or solutions?

Thank you in advance!


Solution

  • You can fix this by adding activeIcon property to each todo item and toggle them specifically like:

    data: {
       todos: [
        { text: "Learn JavaScript", id: "Location4", activeIcon: false },
        { text: "Learn Vue", id: "Location3", activeIcon: false },
        { text: "Play around in JSFiddle", id: "Location2", activeIcon: false },
        { text: "Build something awesome", id: "Location1", activeIcon: false }
      ]
    }    
    

    and the update starLocation method like:

    starLocation(id) {
      try {
         var todo = this.todos.find(t => t.id === id)
         todo.activeIcon = !todo.activeIcon;
      } catch (error) {
        alert(error);
      }
    }
    

    and finally update your template like:

    <p 
      @click="starLocation(item.id)"
      :class="{ activeIcon: item.activeIcon}"
      :key="item.id"> STAR
    </p>
    

    Working Demo