首页 > 解决方案 > 表单输入字段之间的计算

问题描述

我想寻求一点帮助。我是一个 Vue 的初学者,但是做一个简单的计算器。

问题是:三个表格输入了两个值并在第三个中计算。

最好我将所有三个空白,当数据输入到两个时,计算在第三个中呈现。哪两个没关系。不幸的是,我无法弄清楚,所以我使用了两个特定的值,并在第三个中使用计算进行计算。我希望这样,无论您输入哪两个,第三个都会显示我需要的计算。

此外,正如您从代码中看到的那样,我有多个 if 语句。我相信有一个更好的方法来编写这个。归根结底,我的代码可以工作,但在使用我需要的多个 if 语句时会变得很长。

new Vue({
  el: "#app",
  data: {
    value1: null,
    value2: null
  },
  computed: {
    a_ratio() {
      var a_number = parseInt(this.value2) / parseInt(this.value1);
      return a_number.toFixed(1);
    },

    calculation() {
      if (this.value1 < 100 && this.value2 > 0) {
        var val = parseInt(this.value2) / 10 || 0;
        return val.toFixed(1);
      }
      if (this.value1 >= 100 && this.value2 > 0) {
        var val = parseInt(this.value2) / 20 || 0;
        return val.toFixed(1);
      }
    }
  }
});

标签: javascriptvue.js

解决方案


漂亮多了:)

new Vue({
  el: "#app",
  data: {
    value1: null,
    value2: null
  },
  computed: {
    a_ratio() {
      var a_number = parseInt(this.value2) / parseInt(this.value1);
      return a_number.toFixed(1);
    },

    calculation() {
      if (this.value2 <= 0) return;
      let divider;

      if (this.value1 < 100) {
        divider = 10;
      } else if (this.value1 >= 100) {
        divider = 20;
      }

      return (parseInt(this.value2) / divider || 0).toFixed(1);
    }
  }
});

推荐阅读