1

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>

1
  • num should be a property of a food object and you should increase and decrease that. Commented Aug 16, 2019 at 9:36

2 Answers 2

1

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--
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

oh ! I got it! I add num to my json api and it works! thanks for your help!
-1
 <div v-for="(selected, index) of items">
   {{index+1}}
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.