计算属性-价格netto和每一项的价格

时间:2018-07-01 09:36:40

标签: javascript vue.js computed-properties

我有一系列商品,上面有金额和价格(税前)。我想计算一件商品的净价格和价格。我还具有一个过滤器,该过滤器允许显示货币,并希望在创建的计算属性旁边显示该过滤器。计算的属性和在它们旁边显示过滤器不起作用。我该怎么做才能使其正常工作? JSFiddle here

HTML:

<table>
    <thead>
      <tr class="table-head">
        <th v-for="item in tableHead">{{ item.name }} <span>{{ item.desc }}</span></th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(element, index) in amount">
        <td>{{ element.amount }}</td>
        <td>
          {{ priceNet }}

        </td>
        <td>
          {{ element.price | curr }}
          {{ pricePerItem }}
        </td>
      </tr>
    </tbody>
  </table>

Vue Js:

new Vue({
  el: "#app",
  data: {
    tableHead: [
      { name: 'amount', desc: '' },
      { name: 'price', desc: '(net)' },
      { name: 'price', desc: '(pre-tax)' }
    ],
    amount: [
      { amount: 100, price: 80.61 },
      { amount: 250, price: 72.10 },
      { amount: 500, price: 79.62 },
      { amount: 1000, price: 100.20 },
      { amount: 2500, price: 147.60 },
      { amount: 5000, price: 232.56 }
    ]
  },
  computed: {
    priceNet() {
      this.amount.forEach((element) => {
        let net = (element.price / 1.23);
        return net;
      })
    },
    pricePerItem() {
      this.amount.forEach((element) => {
        let priceP = element.price / element.amount;
        return priceP;
      })
    }
  },
  filters: {
    curr: (value) => {
      return `${value.toFixed(2)} euro`
    }
  }
})

1 个答案:

答案 0 :(得分:1)

您想要computed而不是methods

methods: {
  priceNet(price) {
    return price / 1.23
  },
  pricePerItem(price, amount) {
    return price / amount
  }
},

然后,在您的html中更新绑定:

 <tr v-for="(element, index) in amount">
    <td>{{ element.amount }}</td>
    <td>
      {{ priceNet(element.price) | curr }}

    </td>
    <td>
      {{ element.price | curr }}
      {{ pricePerItem(element.price, element.amount) | curr }}
    </td>
  </tr>

更新的小提琴:

https://jsfiddle.net/75Lk2tpe/1/