vuejs 表单计算 属性
vuejs form computed property
我在 VueJS 中有一个简单的表单,我想为其中一个表单字段计算 属性。我希望计算的 属性 在用户输入数据时计算,然后在将表单提交到服务器之前保存为数据 属性。
<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;
}
}
});
operatingIncome
的计算 属性 不会计算,除非我在 formData
数据对象中显式创建 revenue
和 expenses
的属性并更改<input>
给一个字符串插值。关于如何使这项工作有任何建议吗?
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.
声明 formData
的可能子元素应该可以解决问题:
data: {
formData: {
revenue: null,
expenses: null,
operatingIncome: null,
}
},
我在 VueJS 中有一个简单的表单,我想为其中一个表单字段计算 属性。我希望计算的 属性 在用户输入数据时计算,然后在将表单提交到服务器之前保存为数据 属性。
<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;
}
}
});
operatingIncome
的计算 属性 不会计算,除非我在 formData
数据对象中显式创建 revenue
和 expenses
的属性并更改<input>
给一个字符串插值。关于如何使这项工作有任何建议吗?
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.
声明 formData
的可能子元素应该可以解决问题:
data: {
formData: {
revenue: null,
expenses: null,
operatingIncome: null,
}
},