首页 > 解决方案 > 在 vue.js 中为每个循环使用计算数据

问题描述

v-model在使用for<input>标签时,我愿意利用响应式数据更改。

现在我想在循环内有一个值,以便在触发v-for时自动更新。v-model

我在这里做错了什么?

<tr v-for="(service, key) in services" :key="key">
  <td class="left aligned">
    <div class="title" contenteditable="true">{{ service.title }}</div>
    <div class="desc" contenteditable="true">{{ service.description }}</div>
  </td>
  <td class="price">
    <input v-model.number="service.price" type="number" min="0" /> &euro; / day
  </td>
  <td class="quantity">
    <input v-model.number="service.quantity" type="number" min="0" />
  </td>
  <td>
    <div class="total">{{ service.total | currency }} &euro;</div>
    <div class="tva">+{{ service.total | tva(invoice.tax) }} &euro; ({{ invoice.tax }}%)</div>
  </td>
</tr>

每当我更改inputs service.quantityor中的值service.price时,它们都会自动更新,除了service.total.

标签: javascriptvue.js

解决方案


改用一种方法:

export default {
  ...
  methods: {
    getServiceTotal({ price, quantity }) {
      return quantity * price;
    }
  }
  ...
}

在您的模板中:

<div class="total">{{ getServiceTotal(service) | currency }} &euro;</div>

推荐阅读