Skip to content
Advertisement

I want to add counter in for loop in each item.(vue.js)

I’m making cart app with Vue. And trying to make quantity counter, but when I click – or + button, all of items quantity also increase or decrease.

So it seems like I need to give each key for buttons but I don’t know how to do that.

new Vue({
  el: '#app',
  
  data(){
    return {
      foods: [{
        id: 1,
        imgUrl: 'https://image.shutterstock.com/image-photo/healthy-food-clean-eating-selection-260nw-761313058.jpg',
        title: 'Food',
        price: '5,00'
      }],
      num:0
    }
  },

  methods:{
    increase(index){
      this.num++
    },

    decrease(index){
      this.num --
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div
    class="items" v-for="(food,index) in foods"
    v-bind:food="food"
    v-bind:key="food.id"
  >
    <img class="foodImg" v-bind:src="food.imgUrl" />
    <h4>{{food.title}}</h4>
    <p>{{food.price}}€</p>

    <button :class="index" class="minus" @click="decrease">-</button>
    {{num}}
    <button :class="index" class="add" @click="increase">+</button>
    <button type="submit">Add to cart</button>
  </div>
</div>

Advertisement

Answer

Your num variable shouldn’t be in your component and instead you should attach it to your food items. Otherwise the num variable is shared across all of them.

Please don’t forget to give your food items the num variable before you pass the foods array to your component so its not initially empty.

try this:

<div class="items" v-for="(food,index) in foods" v-bind:food="food" v-bind:key="food.id">
    <img class="foodImg" v-bind:src="food.imgUrl"/>
    <h4>{{food.title}}</h4>
    <p>{{food.price}}€</p>
    
    <button :class="index" class="minus" @click="increase(food)">-</button>
    {{food.num}}
    <button :class="index" class="add" @click="decrease(food)">+</button>
    <button type="submit">Add to cart</button>
</div>

Script

<script>
export default {
    name:'Products',
    props:['foods'],
    methods:{
        increase(food){
            food.num++
        },

        decrease(index){
            food.num--
        }
    }
}
Advertisement