Embarking on my Vue journey with a simple example, I am attempting to calculate the sum of items based on the provided data. If you wish to explore the complete example, it can be accessed in this jsffile.
Here is the component structure:
Vue.component('items-table', {
props: ['items', 'item', 'total'],
template: `
<div>
<table>
<thead>
<tr>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr
v-for="item of items"
v-bind:key="item.id"
>
<td>{{item.desc}}</td>
<td class="price">{{item.price}}</td>
</tr>
</tbody>
</table>
<div>Total items: {{items.length}}</div>
<div>Total price: {{total}}</div>
</div>
`
});
In the current implementation below, the console outputs an empty array, leading to always returning 0 as the total sum:
new Vue({
el: '#app',
data:{
items: []
},
computed: {
total: function(){
console.log(this.items);
return this.items.reduce(function(total, item){
return total + item.price;
},0);
}
},
mounted() {
console.log('app mounted');
}
});
To start off, here is the initial set of data that will drive the display, manipulation, and calculations:
<div id="app">
<items-table v-bind:total="total" v-bind:items="[
{ id: 1, desc: 'Banana', price: 10 },
{ id: 2, desc: 'Pen', price: 5 },
{ id: 3, desc: 'Melon', price: 5 }
]"></items-table>
</div>
The key challenge lies in the fact that the total displayed in {{total}} always registers as 0. It seems like the items array fails to update when passed via v-bind:items (could it be non-reactive?). Any assistance or insights would be greatly appreciated.
Edit: Additional Context
All data feeding into the components originates from plain PHP files. CRUD operations are currently not supported. Hence, it is crucial for the data to seamlessly bind directly from the tags.