Have two input in the child components but focusing on the first input which emits the eKey. The second input which specifies the amount is working perfectly.
In the parent component I want the input value of the first input to pushed in the epensesKey array which is set in the data() section.
Note: The bigger picture is for me to send a POST request to my Express Api with the expenseKey and expenseValue array as a key/value pair
Child Component
<template>
<div class="input">
<input
type="text"
placeholder="Expense"
@input="$emit('eKey', $event.target.value)"
/>
<input
type="number"
placeholder="Amount"
@input="$emit('input', {
value: $event.target.value,
id
})"
/>
</div>
</template>
<script>
export default {
name: "formInput",
props: {
id: Number,
eKey: Array
}
};
</script>
Parent Component
<template>
<div class="container">
<h1>Budget Form</h1>
<div class="form">
<form action>
<div class="topForm">
<label for="monthlypay">Monthly pay</label>
<input type="number" name="monthlypay" id="monthlypay" v-model="earnings" />
</div>
</form>
<h2>Expenses</h2>
<form-input v-for="(n,idx) in count" :key="n" :id="idx" :ekey="expensesKey"
@ekey="ekey = $event" @input="getExpenseValue">
</form-input>
<button @click="addInputs">Add Expense</button>
<button @click="deleteInputs">Delete</button>
<button type="button" @click="submitBudget">Submt</button>
<p>Total Monthly Income: {{ earnings }}</p>
<p>Total Expense: {{ totalExpense }}</p>
<p>Money left: {{ getDifference }}</p>
</div>
</div>
</template>
<script>
import axios from "axios";
import formInput from "../components/Input.vue";
export default {
components: {
"form-input": formInput
},
name: "form",
data() {
return {
count: 0,
earnings: "",
expensesValue: [],
expensesKey: [],
totalExpense: ""
};
},
methods: {
addInputs: function() {
this.count++;
this.expensesValue[this.count - 1] = 0;
},
deleteInputs: function() {
this.count--;
this.expensesValue.pop();
this.setTotalExpense();
},
getExpenseValue(data) {
this.expensesValue[data.id] = parseInt(data.value, 10) || 0;
this.setTotalExpense();
},
setTotalExpense() {
console.log(this.expensesValue);
this.totalExpense = this.expensesValue.reduce((sum, val) => {
return sum + val;
}, 0);
},
submitBudget() {
axios
.post("http://localhost:3000/budget", {
earning: this.earnings,
expenses: this.expensesKey
})
.then(response => {
console.log(response.data);
})
.catch(e => {
console.error(e);
});
}
},
computed: {
getDifference() {
return this.earnings - this.totalExpense;
}
}
};
</script>