One of the challenges I'm facing in my Vue app is calculating the total of subtotals.
Every component has its own subtotal that depends on user input. I need to combine these individual subtotals and display the result in an input field outside of the components.
I'm struggling with how to properly reference the component subtotals from outside of the components. Would it be a good approach to add a computed property to the #app for this purpose?
<div id="app">
<h1 style="padding: 2em 0 1em">Vue.JS Loop 2</h1>
<div class="total">
<input :value="form.income" @change="updateIncome" type="number" class="form-control" name="income" id="income" placeholder="Income">
<!--Add all subtotals here-->
<input :value="form.expenses" @change="updateExpenses" type="number" step="any" class="form-control" name="expenses" id="expenses" placeholder="Expenses">
<hr/>
<input v-model="form.dispIncome" type="number" step="any" class="form-control" name="dispIncome" id="dispIncome" placeholder="Disposable Income">
</div>
<div class="budget-container">
<div class="budget" v-for="budget in budgets">
{{budget}} Expenses
<budget-line></budget-line>
</div>
</div>
</div>
<script>
var budgetLine = Vue.extend({
template: `
<div>
<p id="result"><strong>Total:</strong> $ {{ totalQty }} </p>
<div class="row" v-for="item in items">
<input type="text" placeholder="Item"></input>
<input type="text" placeholder="How much?" v-model="item.qty"></input>
<button @click="addItem">+</button>
<button @click="removeItem">-</button>
</div>
</div>
`,
data: function() {
return { items: [] };
},
computed: {
totalQty() {
return this.items.reduce((total, item) => {
return total + Number(item.qty);
}, 0);
},
},
methods: {
addItem() {
this.items.push({
qty: 0
});
},
removeItem(item) {
this.items.pop(item);
}
},
mounted() {
this.addItem()
}
});
var budgetApp = new Vue({
el: '#app',
data: {
budgets: ['One', 'Two', 'Three'],
form: {
income: 0,
expenses: 0,
dispIncome: 0
}
},
components: {
'budget-line': budgetLine
},
methods: {
updateIncome(event) {
this.form.income = event.target.value
this.form.dispIncome = this.form.income - this.form.expenses
},
updateExpenses(event) {
this.form.expenses = event.target.value
this.form.dispIncome = this.form.income - this.form.expenses
}
}
});
</script>