2017-01-11 34 views
0

我是Vue.js的新手,我似乎無法弄清楚如何更改數據格式。目前它使用以下結構。如何使用Vue.js訪問計算函數中的數組數據

app.js:

new Vue({ 
    el: '#app', 
    data: { 
    price: 0, 
    shipping: 0, 
    handling: 0, 
    discount: 0 
    }, 
    computed: { 
    total: function() { 
     return ((
     this.price * 100 + 
     this.shipping * 100 + 
     this.handling * 100 - 
     this.discount * 100 
    )/100).toFixed(2) 
    } 
    } 
}) 

的index.html:

<div id="app" class="row"> 
    <currency-input label="Price" v-model="price"></currency-input> 
    <currency-input label="Shipping" v-model="shipping"></currency-input> 
    <currency-input label="Handling" v-model="handling"></currency-input> 
    <currency-input label="Discount" v-model="discount"></currency-input> 

    <p class="medium-12 columns">Total: ${{ total }}</p> 
</div> 

http://codepen.io/pixelasticity/pen/rjeVgz

我想將數據改變爲以下,或一些變體,但它不」工作。

app.js:

new Vue({ 
    el: '#app', 
    data: { 
    products: [ 
     { 
     price: 0, 
     shipping: 0, 
     handling: 0, 
     discount: 0 
     } 
    ] 
    }, 
    computed: { 
    total: function() { 
     return ((
     this.products[0].price * 100 + 
     this.products[0].shipping * 100 + 
     this.products[0].handling * 100 - 
     this.products[0].discount * 100 
    )/100).toFixed(2) 
    } 
    } 
}) 

我缺少什麼?

+0

爲什麼要將數據更改爲產品數組? – Stephen

+0

這樣我就可以擁有多種不同但價格可調的產品,運費和折扣。我實際上想要在子組件中輸入價格。 –

回答

0

您還必須更新v-model指令中的屬性。

<currency-input label="Price" v-model="products[0].price"></currency-input> 
<currency-input label="Shipping" v-model="products[0].shipping"></currency-input> 
<currency-input label="Handling" v-model="products[0].handling"></currency-input> 
<currency-input label="Discount" v-model="products[0].discount"></currency-input> 

這個問題反映了你的問題。但是,您的數據結構似乎有線。爲什麼你需要一個數組,而你只求和第一個產品?無論如何,你的total計算出來的財產並沒有總結所有其他產品。

+0

謝謝。我知道它必須是那樣的明顯。 我想要它的原因是這樣格式化,所以我可以有多個產品具有不同的默認價格和運費。 –

相關問題