2016-07-26 42 views
5

如何從父項訪問Vue中組件的計算屬性?從父項訪問Vue中組件的計算屬性

在這個例子中,我有項目組件的車,我想計算並顯示車項目的總和:

cart.js

var vm = new Vue({ 

    el: '#cart', 

    components: { 
    cartItem: require('./components/cart-item.js'), 
    }, 

    data: { 
    items: [ 
     { name: 'apple', qty: 5, price: 5.00 }, 
     { name: 'orange', qty: 7, price; 6.00 }, 
    ], 
    }, 

    computed: { 
    // I want to do something like this and access lineTotal from cart 
    cartTotal: function() { 
     return this.items.reduce(function(prev,curr) { 
     return prev + curr.lineTotal; 
     }, 0) 
    } 
    } 
}); 

車-item.js

module.exports = { 
    template: require('./cart-item.template.html'), 
    props: ['fruit'], 
    computed: { 
     lineTotal: function() { 
     return this.fruit.price * this.fruit.qty; 
     } 
    }, 
}; 

主HTML

<li v-for="item in items" is="cart-item" :fruit="item"> 

... 

@{{ cartTotal }} 

如何訪問用於總結cartTotal的每個購物車項目的lineTotal屬性?

請注意,我不想重做在lineTotal中完成的計算,而是直接使用計算的屬性。

+0

雖然@ gurghet提供了技術上正確的答案,我會建議不要訪問孩子這樣的東西。 計算所需的所有數據已經​​存在於購物車中,計算基本上是單線。從孩子訪問數據將至少像在父母本身進行計算一樣複雜。 –

+0

購物車是一個簡單的例子,我用來說明我的問題的性質。如果計算不是單向的,那麼組件將是解耦購物車項目邏輯的好方法。除了直接訪問孩子而不對父母進行計算之外,您是否有任何建議? – howellmartinez

回答

6

您必須命名孩子,例如通過v-ref指令。然後從父母你解決孩子屬性與this.$refs.mychild.myproperty

+0

this。$ refs爲我返回一個空Object {}。我錯過了什麼? – howellmartinez

+0

你有沒有設置v-ref? – gurghet

+0

Herm ...我剛看到你的jsfiddle ...超過1個東西是錯的。您在純JavaScript中使用過濾器('| json'),您也正在處理一個正常的''元素,就像它是一個組件一樣。我會告訴你一個完整的例子,這樣你就可以從中學習,而不是修復你的問題,這顯示了一個有點奇怪的方法來解決問題。我會在這個聊天室給你發送鏈接:https://chat.stackoverflow.com/rooms/118302/vuejs – gurghet