如何从计算值中对Vue.js中的v-for的值求和

gs-*_*-rp 4 vuejs2

我正在尝试对使用vuejs在v-for内计算的值求和,但是我认为它不起作用,因为我无法从v-for内的计算值访问值。

我需要在{{total}}中以用户身份显示总价值,即 v-model.number="totalItem(item)"

有人可以给我一些指示吗?谢谢。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>

<div id="app">

    <button v-on:click="add">ADD ROW</button>

    <p>$: {{ total }}</p>

    <ul>
        <li v-for="(item, index) in items">
            <input type="text" v-model="item.name">
            <input type="number" v-model.number="item.quantity" min="1">
            <input type="number" v-model.number="item.price" min="0.00" max="1000000000.00" step="0.01">
            <input type="number" v-model.number="totalItem(item)" readonly>
            <button v-on:click="remove(index)">X</button>
        </li>
    </ul>



    <pre>{{ items | json}}</pre>


</div>


<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="vuejs.js"></script>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

JavaScript-Vue.js

new Vue({
  el: '#app',
  data: {
    items: [{name: '', quantity: '', price: ''}]
  },
  methods: {
    add: function () {
      this.items.push({
        name: '',
        quantity: '',
        price: '',
        subTotal: ''
      })
    },
    remove: function (index) {
      this.items.splice(index, 1)
    },
    totalItem: function (item) {
      return item.price * item.quantity;
    }
  },
  computed : {
    total: function() {
      let sum = 0;
      return this.items.reduce((sum, item) => sum + item.price, 0);
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

Men*_*eng 7

  1. 为了
computed: {
  totalItem: function(){
      let sum = 0;
      for(let i = 0; i < this.items.length; i++){
        sum += (parseFloat(this.items[i].price) * parseFloat(this.items[i].quantity));
      }

     return sum;
   }
}
Run Code Online (Sandbox Code Playgroud)
  1. ForEach
  computed: {
    totalItem: function(){
      let sum = 0;
      this.items.forEach(function(item) {
         sum += (parseFloat(item.price) * parseFloat(item.quantity));
      });

     return sum;
   }
}
Run Code Online (Sandbox Code Playgroud)


gs-*_*-rp 6

我找到了答案。这很简单。

v-model.number="item.total = item.quantity * item.price"
Run Code Online (Sandbox Code Playgroud)


小智 5

在父组件中做这样的事情:

computed: {
  total: function(){
  return this.items.reduce(function(prev, item){
  return sum + item.price; 
  },0);
 }
}
Run Code Online (Sandbox Code Playgroud)