【问题标题】:Computed property - price netto and price per one item计算财产 - 净价和每件价格
【发布时间】:2018-12-09 20:26:34
【问题描述】:

我有一系列包含数量和价格(税前)的商品。我想计算每件商品的净价和价格。我还有一个允许显示货币的过滤器,并希望在创建的计算属性旁边显示该过滤器。计算属性和在它们旁边显示过滤器不起作用。我能做些什么来让它们工作? 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`
    }
  }
})

【问题讨论】:

  • 请添加 whar 不起作用。顺便说一句,forEach 不会返回与undefined 不同的东西。如有必要,请使用 map 代替新数组。
  • @connexo 我的小提琴怎么了?
  • 你的计算函数什么都不做。 Computed需要返回一个值。
  • 你的例子也不行。

标签: javascript vue.js computed-properties


【解决方案1】:

你想要methods而不是computed

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/

【讨论】:

  • 确保pricePerItem中的数量不能为0。
猜你喜欢
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-19
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多