0

i am building a simple cart using Vuejs. I am having trouble calculating the total in the cart. It seems not to be adding the price together but displaying the numbers together like if i have two items in the cart at prices 10 and 15 it displays "1015" where the answer should be "25"

Cart.Vue

<template>
 <div class="container">
  <h1>Your Cart</h1>
   <div class="center" v-for="item in shoppingCart">
    <div class="col-md-8 cart-item">
      <div class="row">
        <div class="item-img pull-left">
          <img class="media-object" v-bind:src="item.thumbnailUrl">
        </div>
        <div class="item-info pull-right">
          <h5>{{item.title}}</h5>
          <h5>{{item.price}}</h5>
          <button class="btn btn-danger" v-on:click="removeFromCart(item.id)">Remove From Cart</button>
        </div>
      </div>
    </div>
  </div>
  <div class="total">
    <h3> Total : &euro;{{total}} </h3>
  </div>
 </div>
</template>

<script>
  export default {
   name: 'Cart',
   props: ['shoppingCart'],
   data() {
    return {
     }
  },
  computed: {
    total() {
      return this.shoppingCart.reduce((acc, item) => acc + item.price, 0);
    }
  },
  methods: {
    removeFromCart: function(productId) {
      console.log('remove product from cart', productId);
      this.$emit('removeFromCart', productId);
    }
   }
  }
</script>

Sample of what it looks like on the web

Still only very new to Vuejs, so any feedback would be great, thanks!

1 Answers1

1

What you're running into is string addition instead of numeric addition. In your example, "acc" and/or "item.price" are actually string values. When you add the string "10" to the string "15", you get "1015", which is correct. Try converting them to numbers first:

Something like this would work: acc += (item.price * 1)

Although, the "correct" solution would probably be something like this: acc += parseFloat(item.price), or acc += Number(item.price).

See converting a string to a number.

Steven Jeffries
  • 3,522
  • 2
  • 20
  • 35