Vince
Vince

Reputation: 629

vuejs form computed property

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?

Upvotes: 1

Views: 2500

Answers (1)

ceejayoz
ceejayoz

Reputation: 179994

https://v2.vuejs.org/v2/guide/reactivity.html

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method.

Declaring the possible sub-elements of formData should do the trick:

data: {
    formData: {
        revenue: null,
        expenses: null,
        operatingIncome: null,
    }
},

Upvotes: 3

Related Questions