如何为输入设置onkeyup事件

问题描述

我有调用产品最大数量的 GET 请求方法

data() {
    return {
      itemmaxQty: ''
    }
  },methods: {
   setMaxItem(event) {
       const value = event.target.value;
       console.log('value',value);
       if(value > this.maxItemQty) {
          value = this.maxItemQty
       } else if(value < 0) {
         value = 0
       }
   },maxItem(){

    let item_id = this.itemID;
                        
      axios.get("./available/" + item_id).then((response) => {
        console.log('maxItem',response.data); \\output: maxItem 9
        this.maxItemQty = response.data;
      })
    }
  }

如何设置 onKeyUp 属性,以便当用户输入的数量超过 maxItem 时,输入值将自动更改 = maxItem 值?

<input
  type="number"
  min="1"
  onkeypress="return event.charCode >= 48 && event.charCode <= 57"
  name="quantity" 
  id="quantity" 
  class="form-control" 
  placeholder="1" 
  value="1" 
  @keyUp="setMaxItem()"
>

解决方法

请试试这个代码

<input
  type="number"
  min="1"
  onkeypress="return event.charCode >= 48 && event.charCode <= 57"
  name="quantity" 
  id="quantity" 
  class="form-control" 
  placeholder="1" 
  value="1" 
  onkeyup="setMaxItem()"
,

最简单的方法是创建一个watcher,首先你需要制作一个v-model,它将绑定输入元素值和反应性vue数据

<input
    type="number"
    min="1"
    name="quantity" 
    id="quantity" 
    class="form-control" 
    placeholder="1"
    v-model="inputedNumber"
>

然后在数据中创建相同的属性

data() {
    return {
        itemMaxQty: '',inputedNumber: 1,}
},

现在我们可以制作一个观察者

watch: {
    inputedNumber(newValue) {
        this.setMaxItem().then(() => {
            if (newValue > this.maxItemQty) {
                this.inputedNumber = this.maxItemQty
            }
        })
    }
}
,

我想评论@ZloiGoroh,但我的积分不够。

我在代码 setMaxItem 中没有看到返回承诺。而且我不认为这个想法是在每次按键时进行 api 调用来确定 itemMaxQty。如果是这样,我仍然不建议这样做。

由于问题也有计算最小值的代码,我会改变观察者的实现:

inputedNumber(newValue) {
  if (newValue > this.maxItemQty) {
    this.inputedNumber = this.maxItemQty
  } else if (newValue < 0) {
    this.inputedNumber = 0;
  }
}

或者只用 Math.min()Math.max() 限制值。

watch: {
  inputedNumber(newValue) {
    /* 
      Math.max -> returns the highest of the two
      Math.min -> returns the lowest of the two
      the lowest number allowed is 0
      the heighest number is either the newValue 
      or if that value is heigher than maxItemQty maxItemQty itself
    */

    this.inputedNumber = Math.max(0,Math.min(newValue,this.maxItemQty)
  }
}

有些人可能会争论 inputedNumber 即使值在最小值和最大值之间也总是被更新,但这种原因造成的性能损失是可以忽略的,不能为零。

即使问题是关于按键的,我也不会在你的情况下走那条路。

ps。我的唯一目的是提供一个最小的解决方案,而不是命名和/或重构最佳实践的答案

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...