1

i'm making a list of items with vuejs v-for loop. I have some API data from server.

items: [
   {
       foo: 'something',
       number: 60
   },
   {
       foo: 'anything',
       number: 15
   },
   {
       foo: 'text',
       number: 20,
   }
]

Template

<div v-for="(item,index) in items" :key="index">
     <div :class="{ active: ????}" @click="toggleActive">
          {{ item.foo }} 
          {{ item.number }}
     </div>
</div>

JS

methods: {
    toggleActive() {
        //
    }
}

I need following: When i'm clicking on div add class active, if i have already active class - remove active class.( toggle ). Also i can select multiple items.

How can i do this? I don't have boolean variable in items array, and i shouldn't move item in a separate component

mtleppay
  • 281
  • 8
  • 15

2 Answers2

7

Here you go.

new Vue({
  el: "#app",
  data: {
    items: [{
        foo: 'something',
        number: 60
      },
      {
        foo: 'anything',
        number: 15
      },
      {
        foo: 'text',
        number: 20,
      }
    ]
  },
  methods: {
    toggleActive(index) {
      let item = this.items[index];

      item.active = !item.active;

      this.$set(this.items, index, item);

    }
  }
})
.active {
  color: red;
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<div id="app">
  <div v-for="(item,index) in items" :key="index">
    <div :class="{ active: item.active}" @click="toggleActive(index)">
      {{ item.foo }} {{ item.number }}
    </div>
  </div>
</div>

Here's a JS Fiddle: https://jsfiddle.net/eywraw8t/250008/

Julian Paolo Dayag
  • 3,562
  • 3
  • 20
  • 32
3

App.vue

<template>
     <div>
        <div 
        v-for="(item, i ) in items" 
        :key="i"
        :class="{ active: i === activeItem}"
        >
         // some looped items from data here
         // button for active toggle 
            <button @click="selectItem(i)"> make item active </button>
        </div>
    </div>
</template>
 

Data and Methods

<script>
export default {
    data() {
        return {
            activeItem: null,
        };
    },
    methods: {
        selectItem(i) {
            this.activeItem = i;
        },
    },
};
</script>
David Buck
  • 3,752
  • 35
  • 31
  • 35