0

I have faced an issue when doing a simple shopping cart app in vue js 2 Here is the code I have:

blank cart item array for when I press add to cart button then that particular product will be pushed in this array.

data () {
    return {
      cartItems: []
    }
}

add to cart method:

methods: {
    addToCart (product) {
      product.quantity += 1
      this.cartItems.push(product)
    }
}

Template view:

<ul>
   <li v-for="item in items">
        <pre>
            {{item.name}} -- {{item.quantity}}
        </pre>
    </li>
</ul>

in the browser, I got this:

right side 1 and 2 value is the quantity of that product

note: right side 1 and 2 value is the quantity of that product but I want something like this.

right side 1 and 2 value is the quantity of that product

note: right side 1 and 2 value is the quantity of that product

If I use vue js 1 instead of vue js 2 then same code gives me browser view like 2nd screenshot I attached.

Please, anybody, help me to solve this.

3 Answers 3

2

The problem is you push your product to array both times. Check if product exists in cartItems array, if not - add, else - update product quantity

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain me little clearly? can you give me some example that will be a big help for me.
Thanks, brother you have done a great help for me. Actually, I have missed those "indexof" logic that you have done. Thanks a lot. :)
1

How du you create the new products? Do you reference the same object when calling addToCart or do you do some kind of deep copy or extend? If your adding the same reference multiple times they will all have the same quantity.

v-for="item in items" this should be ìf cartItems if you are not using pseudo code as example.

2 Comments

Can you explain me little clearly? can you give me some example that will be a big help for me.
It depends on the source of your movies. You need a new object or both show the same quantity. They have a similary problem stackoverflow.com/questions/42611369/…
0

that is because you increment number of product and again after that you push same product to list . you should check if that item is in the list or not

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.