Tanmay
Tanmay

Reputation: 3189

Computed property is not being updated

I have a data property, which is an empty array:

data: () => ({
    total: [],
});

A method called getAmount():

getAmount(item){ // gets individual amount and pushes it to the total array
    var amount = 0;
    // Skipping the amount calculation to keep the 
    // question as small as possible
    amount = item.price + 10;
    this.total[this.total.length] = amount;
    return amount;
}

And a computed property called getTotal():

getTotal(){
    if(this.total.length > 0){
      return this.total.reduce((x,y) => x+y);
    } else {
      return 0;
    }
  },

In the template I am accessing the getAmount() method and getTotal computed property like this:

<v-data-table
  :headers="headers"
  :items="orderShares"
  hide-actions
  class="elevation-1"
>
  <template slot="items" slot-scope="props">
    <td class="text-xs-left">{{ props.item.order.order_code }}</td>
    <td class="text-xs-left">{{ getAmount(props.item) }}</td>
  </template>
</v-data-table>

<p> Total Amount: {{ getTotal }} </p>

The total amount always remains 0. But what I was expecting is that it should update as many times as the getAmount() method is called. Because getAmount() triggers a change in the total prop, theoretically, computed property getTotal should also be updated since it depends on total. But that's not what's happening here. How can I fix this?

Upvotes: 0

Views: 106

Answers (1)

Bill Criswell
Bill Criswell

Reputation: 32941

You likely want to do this in your method instead due to array detection caveats (https://v2.vuejs.org/v2/guide/list.html#Caveats)

this.total.push(amount)

Also, that getTotal computed can simply be:

return this.total.reduce((x, y) => x + y, 0)

Upvotes: 1

Related Questions