How do you access the computed properties of components in Vue from the parent?
In this example, I have a cart with item components and I want to compute and display the sum of the cart items:
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)
}
}
});
cart-item.js
module.exports = {
template: require('./cart-item.template.html'),
props: ['fruit'],
computed: {
lineTotal: function() {
return this.fruit.price * this.fruit.qty;
}
},
};
main html
<li v-for="item in items" is="cart-item" :fruit="item">
...
@{{ cartTotal }}
How do I access the lineTotal
properties of each cart-item to use in summing cartTotal
?
Note that I do not want to redo the calculations done in lineTotal
but instead use the computed properties directly.
Yes, you can setup watcher on computed property, see the fiddle.
In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.
We can access the root instance of from a child component with the $root property. The code above created a rootFoo computed property from the root Vue instance's foo component and displayed it inside the foo component. So we get foo displayed.
You have to name the children, for example by means of the v-ref
directive. Then from the parent you resolve the children properties with this.$refs.mychild.myproperty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With