简体   繁体   English

如何使用 Vue.js 检查值是否在数字范围内

[英]How to Check if a value is within a range of numbers using Vue.js

I am creating a simple calculator which calculates the discount percentage when entering the price in the field, I have two different discount types.我正在创建一个简单的计算器,用于在字段中输入价格时计算折扣百分比,我有两种不同的折扣类型。

  1. If the price is in 10-90 range you get a 50%-discount.如果价格在10-90范围内,您将获得 50% 的折扣。
  2. If the price is in 100-900 range you get a 90%-discount.如果价格在100-900范围内,您将获得 90% 的折扣。

Problem: When I am entering 100 in the input field both type is selected, my aim is to select only second type of discount.问题:当我在输入字段中输入100 ,两种类型都被选中,我的目标是只选择第二种类型的折扣。

Code SandBox 代码沙盒

You can pass discount to your method:您可以将折扣传递给您的方法:

 new Vue({ el: '#demo', data() { return { price: "", cascadeSugg: [ { id: 3, title: "10-90USD take 50% discount", min: 10, max: 90, discount: 50, created_at: "2021-10-28T03:04:33.000000Z", updated_at: "2021-10-28T03:41:49.000000Z", start_date: "2021-10-28", end_date: "2021-10-31", }, { id: 4, title: "100-900USD take 90% discount", min: 100, max: 200, discount: 90, created_at: "2021-10-28T03:54:28.000000Z", updated_at: "2021-10-28T03:54:28.000000Z", start_date: "2021-10-28", end_date: "2021-10-31", }, ], }; }, methods: { setActiveRange(min, max, disc) { let total = this.price; if(total && total <= 99 && total >= min) { return true } else if ((total && total >= 100 && disc > 50)) { return true; } }, }, }) Vue.config.productionTip = false Vue.config.devtools = false
 #app { font-family: "Avenir", Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } .active { color: #F48245; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="demo"> <div class="cascade-discount"> <input type="text" v-model="price" /> <div class="cascade-item" v-for="cascade in cascadeSugg" :key="cascade.id" > <p class="m-0" :class="{ active: setActiveRange(cascade.min, cascade.max, cascade.discount) }" > {{ cascade.title }} </p> </div> </div> </div>

Well, the problem is that setActiveRange function is working as you have written it - basically, it will return true every time the 'total > price' condition is fulfilled.好吧,问题是 setActiveRange 函数正在按照您编写的方式工作 - 基本上,每次满足“总计 > 价格”条件时它都会返回 true。 Remove that part and it is gonna work.删除那部分,它会工作。 Code sample:代码示例:

 methods: {
    setActiveRange(min, max) {
      let total = this.price;
      if (total && total >= min && total <= max) {
        return true;
      }
    }
  }

You can use a simple if-else statement to check the range of the values您可以使用简单的 if-else 语句来检查值的范围

if(price => 10 && price <= 90){
//get 50% Discount
}else if(price => 100 && price <= 900){
//get 90%Discount
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM