如何根据一个元素显示正确的计算值?

时间:2019-05-13 19:12:53

标签: javascript vue.js

我有这个“ roi计算器”,用户可以在其中排列一些标签。 而且,我有一个范围叫做“ onlineRevenue”。 这个想法是根据onlineRevenue数字提供最佳计划。

但是,为此,我有局限性

  • 如果onlineRevenue少于100 000,我提供“ essentialYear”;
  • 如果在线收入在10万到30万之间,我会提供“ accelerateYear”;
  • 如果在线收入在30万到50万之间,我提供“终极”;

如何使用vue对变量“ subscriptionFee”添加此限制,以了解上述规则?

例如,有人建议使用直接编号而不使用数据

          subscriptionFee: function() {
          var feesuggest = this.onlineRevenue <=100000;
          return this.essentialYear;
        },

但是这个想法是生成一个变量,如果值是X,则显示该变量。有了上面的这段代码,我无法在值之间进行比较。

我创建了一个jsfiddle来处理代码,以便更轻松地理解我的问题。

2 个答案:

答案 0 :(得分:1)

这样的解决方案怎么样?

const tiers = [
    { name: 'essential', min: 0, max: 100000 },
    { name: 'accelerate', min: 100000, max: 300000 },
    { name: 'ultimate', min: 300000, max: 500000 }
];

const subscriptionFee = (amount) => {
  const tierMatch = (tier) => amount >= tier.min && amount < tier.max;
  const reducer = (tierFound, tier) => tierMatch(tier) ? tier : tierFound;
  return tiers.reduce(reducer, false);
};

subscriptionFee(500);

首先要进行一系列迭代,然后减少到单个项目。您仍然需要考虑更大的数字,因为500001会给您带来错误。

答案 1 :(得分:0)

subscriptionFee: function() {
  const x = this.onlineRevenue
  switch (true) {
    case (x <= 100000):
      return this.essentialYear
      break;
    case (x > 100000 && x < 300000):
      return this.accelerateYear
      break;
    default:
      // anything over 300000
      return this.ultimate
  }
}