2016-08-24 106 views
1

如何計算數組中的總數?Vue.js如何計算總數?

我將數據作爲道具傳遞給子組件,並且我卡在這裏。當我控制日誌道具時,它會返回一個非常複雜的對象。我試過this.values.reduce()函數,但它不起作用。

<template> 
<tr v-for="value in values" > 
     <th scope="row">{{$index+1}}</th> 
     <td>{{value.name}}</td> 
     <td>-</td> 
     <td>${{value.total}}</td> 
    </tr> 
<tr> 
    <th></th> 
    <td><strong>Total:{{total}}</strong></td> 
    <td>-</td> 
    <td>-</td> 
    </tr> 
</template> 

<script> 

export default { 



    props: ['values'], 

     ready: function() { 

    } 

} 
</script> 
+0

作品在這裏,請分享更多的代碼 – gurghet

回答

3

如果其他人與我處於相同的情況,我想我會添加這個答案。我需要從嵌套對象中獲取值則減少他們之前他們推到一個數組:

total: function(){ 

    let total = []; 

    Object.entries(this.orders).forEach(([key, val]) => { 
     total.push(val.price) // the value of the current key. 
    }); 

    return total.reduce(function(total, num){ return total + num }, 0); 

} 

它使用ES7 .entries通過它看上去像這樣的對象循環:

orders = { 
    1: {title: 'Google Pixel', price: 3000},  
    2: {title: 'Samsung Galaxy S8', price: 2500}, 
    3: {title: 'iPhone 7', price: 5000} 
    } 

然後,您可以

<span> {{total}} </span> 
+0

有沒有什麼原因喲你將所有的值都推送到一個數組中,而不是像它們那樣求和它們: 'Object.entries(this.orders).forEach(([key,val])=> {total} = {val.price} }); '? –

+0

嗯好問題,我想可能是我使用陣列也填充購物車數據,所以我有分項結算 – Pixelomo

2

正如您所建議的那樣,您可以使用Array#reduce函數。 Starting from this example on SO,您可以根據自己的需要進行調整,只需將value.total添加到總計。

要計算所有值的總和,你可以使用computed properties,這將在你的模板顯示爲{{ total }}

<script> 

export default { 



    props: { 
     values: { 
      type: Array, 
      default: [] 
     }, 
     } 
     ready: function() { 

    }, 
    computed: { 
     total: function() { 
      if (!this.values) { 
       return 0; 
      } 

      return this.values.reduce(function (total, value) { 
       return total + Number(value.total); 
      }, 0); 
     } 
    } 

} 
</script> 

注:這當然會唯一的工作,如果value.total是一個無量綱數(例如1,而不是'1 USD')。否則,你需要去掉reduce函數。

+0

謝謝您的回答,但這個函數返回:0100200應該換貨政與您的模板顯示總300,除了它給出警告,評估表達式時出錯「function total(){ \t return this.values.reduce(function(total,value){ \t return total + value.total; 0); \t}「:TypeError:this.values.reduce不是函數 – OMahoooo

+1

請閱讀:'當然這隻會工作,如果value.total是一個無單位的數字'。你的值需要是Numbers,否則你需要轉換他們到數字我已經添加了一個例子 – nils

+1

是否有可能,'this.values'不是一個數組?或沒有定義?你應該添加一個默認值。我也添加了一個例子(包括道具驗證)。 – nils