javascript - 计算属性未更新

标签 javascript vue.js

我有一个数据属性,它是一个空数组:

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/

相关文章:

javascript - 如何创建一个独立的 DOM 元素?一个不从 parent 那里继承 css 等

javascript - 如何在移动 Openlayers 上禁用 map 旋转

javascript - 正则表达式将有理数文字与小数匹配,但不完整的有理数文字除外

javascript - 有没有办法从输入类型中删除箭头但将其范围仅限于特定组件?

javascript - Node 返回错误 - "route is not defined"

javascript - 如何使用 Angular Js 在下拉菜单中进行按键选择?

javascript - 为什么 Vue 应用程序中 Quasar 抽屉覆盖了 Quasar 工具栏?

components - Vue 组件分隔符

javascript - Jest 中的 'describe' 和 'test' 有什么区别?

vue.js - 带有 Axios 的 Vuejs - 使用获取请求时出现 '' 跨域错误