vuejs 表单计算属性 [英] vuejs form computed property

查看:76
本文介绍了vuejs 表单计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 VueJS 中有一个简单的表单,我想为其中一个表单字段设置一个计算属性.我希望在用户输入数据时计算计算属性,然后在将表单提交到服务器之前将其保存为数据属性.

 
<div><h3>收入</h3><input type="text" v-model="formData.revenue">

<div><h3>费用</h3><input type="text" v-model="formData.expenses">

<div><h3>营业收入</h3><input type="text" v-model="formData.operatingIncome">

</表单>

JS

new Vue({el: '#app',数据: {表单数据:{}},计算:{营业收入(){返回 this.formData.revenue - this.formData.expenses;}}});

operatingIncome 的计算属性不会计算,除非我在 formData 中明确为 revenueexpenses 创建属性> 数据对象并将 更改为字符串插值.关于如何进行这项工作的任何建议?

解决方案

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

<块引用>

由于现代 JavaScript 的限制(以及放弃了 Object.observe),Vue 无法检测属性的添加或删除.由于 Vue 在实例初始化期间执行 getter/setter 转换过程,因此数据对象中必须存在一个属性,以便 Vue 对其进行转换并使其具有反应性.

Vue 不允许向已创建的实例动态添加新的根级响应式属性.但是,可以使用 Vue.set(object, key, value) 方法向嵌套对象添加反应性属性.

声明 formData 的可能子元素应该可以解决问题:

数据:{表单数据:{收入:空,费用:无,营业收入:空,}},

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

这篇关于vuejs 表单计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆