0

Is it possible to make the total reactive? for example, in my basket I have two articles for a price of 18 €, if I add an article I want the total to change without updating the page. my property calculate total returns me for two options: 14,0012,00 I would have liked it to calculate the price of the two options dynamically: 14,00 + 12,00 = 26

thank you for help

<template>
    <div>
      <div >
        
          <div >
            <u>
                <li v-for="item in shop" :key="item.id">
                    {{ item.label}} : {{ item.cost }}€
                </li>
            </u>
            <button @click="addItem">Add</button>
        </div>
       
        <div >
            <u>
                <li v-for="item in shop" :key="item.id">
                    {{ item.label}} : {{ item.cost }}€
                </li>
            </u>
            
        </div>
            <p>{{ total}}</p>
        </div>
    </div>
</template>

<script>
  computed:{
      totalbasket(){
            let total = 0
             this.shop.forEach(item=>{
                total += item.cost
                
            })
             
            return total
        }
}
</script>

tony
  • 199
  • 4
  • 15

2 Answers2

1

It looks like the problem is your item.cost is a string, not a float. Parsing the cost to floats before adding them might do the trick:

 totalbasket(){
   let total = 0
   this.shop.forEach(item=>{
     total += parseFloat(item.cost)
   })
   return total
   }

And at the moment you have {{total}} in your template. You probably want to change this to {{totalBasket}}.

As mentioned by tony19 javascripts parseFloat function does not recognize commas as decimal points. There's a question about how to solve it here.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Lars
  • 710
  • 5
  • 19
0

I would add an Add Button to each item you want to add and then call addItem(item). It would be something like this:

...
<li v-for="item in shop" :key="item.id">
  {{ item.label}} : {{ item.cost }}€
  <button @click="addItem(item)">Add</button>
</li>

Then, the addItem method adds the item, which would trigger totalbasket:

methods: {
  addItem(item) {
    this.shop.push(item)
  },
...
}

And in your template, you should print totalbasket instead of total:

<p>{{ totalbasket }}</p>

This should do it.

Laerte
  • 7,013
  • 3
  • 32
  • 50