我有一个数据属性,它是一个空数组:
data: () => ({
total: [],
});
名为 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;
}
还有一个名为 getTotal()
的计算属性:
getTotal(){
if(this.total.length > 0){
return this.total.reduce((x,y) => x+y);
} else {
return 0;
}
},
在模板中,我访问 getAmount() 方法和 getTotal 计算属性,如下所示:
<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>
总金额始终保持0
。但我期望的是它应该更新与调用 getAmount() 方法一样多的次数。由于 getAmount()
会触发 total
属性的更改,理论上,计算属性 getTotal
也应该更新,因为它依赖于 total
。但这不是这里发生的事情。我该如何解决这个问题?
最佳答案
由于数组检测警告 ( https://v2.vuejs.org/v2/guide/list.html#Caveats ),您可能希望在您的方法中执行此操作
this.total.push(amount)
此外,计算出的 getTotal
可以简单地是:
return this.total.reduce((x, y) => x + y, 0)
关于javascript - 计算属性未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51947487/