Search code examples
javascriptvue.jsvuejs2vue-componentvuex

How to increment a value in state item?


I have a view where I display all items, I want to increase the quantity of each item by clicking add button. I am having issues to set this up - here is what I've came up so far with.

  items: [{ 
      id: 1,
      name: "Car",
      quantity: 1
    },
    { 
      id: 2,
      name: "Car2",
      quantity: 1
    },
]

Mutation which I struggle with -> How do I target a specific item in array here?

increment(state) {
      state.items.quantity++
    }

html

<div v-for="item in items" :key="item.id">
<div>
{{item.name}}
{{item.quantity}}
<button @click="add()">+</button>
</div>

method in html

  add() {
      this.store.commit("increment")
    }

Solution

  • Pass the id to the method and on to the mutation:

    <button @click="add(item.id)">+</button>
    
    add(id) {
       this.$store.commit("increment", id)
    }
    

    Prepare your mutation to receive the id and then find and increment the quantity

    increment(state, id) {
      const item = state.items.find(i => i.id === id);
      item.quantity++;
    }