I have a simple form in VueJS that I would like to have a computed property for one of the form fields. I would like the computed property to be calculated as the user inputs data and then saved as a data property before submitting the form to the server.
<form>
<div>
<h3>Revenue</h3>
<input type="text" v-model="formData.revenue">
</div>
<div>
<h3>Expenses</h3>
<input type="text" v-model="formData.expenses">
</div>
<div>
<h3>Operating Income</h3>
<input type="text" v-model="formData.operatingIncome">
</div>
</form>
JS
new Vue({
el: '#app',
data: {
formData: {}
},
computed: {
operatingIncome() {
return this.formData.revenue - this.formData.expenses;
}
}
});
The computed property for operatingIncome
does not calculate unless I explicitly create properties for revenue
and expenses
within the formData
data object and change the <input>
to a string interpolation. Any suggestions on how to make this work?
https://v2.vuejs.org/v2/guide/reactivity.html
Declaring the possible sub-elements of
formData
should do the trick: