vuejs form computed property

喜欢而已 提交于 2020-06-28 06:02:03

问题


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?


回答1:


https://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,
    }
},


来源:https://stackoverflow.com/questions/46181182/vuejs-form-computed-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!