I'm trying to get the total of a sub object and I want to set that total to a variable of the object:
The total (computed property) is being assigned to the root data.total, I want it to be assigned to data.cart.total
js fiddle at end
<div id="app">
<cart :cart.sync="cart" inline-template>
Ex A: {{total}} <!-- works -->
</br>
Ex B: {{cart.total}} <!-- doesnt work -->
<ul>
<li v-for="product in cart.products">
<h3>{{product.name}}</h3>
<i>{{product.price}}</i>
</li>
</ul>
</cart>
</div>
Vue.component('cart', {
props: ['cart'],
computed: {
total: function() {
return this.cart.products.reduce((a, b) => a + b.price, 0);
}
}
});
new Vue({
el: '#app',
data: {
cart: {
products: [
{
name: 'Hello',
price: 19.99
}
]
},
}
});
jsfiddle:
https://jsfiddle.net/yfn1ggr0/1/
If you need a cart object with the total in it, you can create another computed property with that value in it.
Please, next time make sure to ask the question on the forums or the gitter chat 馃槈
Ok thanks. I want the current existing cart object in data to have a computed total value. I dont understand how to pass the computed value into the cart object.
Below doesnt work
computed: {
cart.total: function() {
return this.cart.products.reduce((a, b) => a + b.price, 0);
}
}
If you need a cart object with the total in it, you can create another computed property with that value in it:
(es6)
computed: {
cartWithTotal () {
return {
total: this.total,
...this.cart
}
}
}
See #1964 - Allow computed properties of subobjects
Most helpful comment
If you need a cart object with the total in it, you can create another computed property with that value in it:
(es6)