在 Vue 中,如果你想要在用户输入时动态地处理输入框的值,并且根据这个值进行一些操作(比如限制最大值、格式化等)
<el-input
type="number"
v-model.number="fileScore"
size="mini"
placeholder="最高分不能超过设定分"
min="0.1"
step="0.1"
:max="maxValue"
@input="onInput(fileScore)">
</el-input>
// 设置分数
onInput(fileScore){
let maxValue = this.maxValue // 总分默认设置10
let grading = fileScore // 当前分
if (grading > maxValue) {
// 如果当前值超过总分,就重新赋值
this.fileScore = maxValue;
return;
}
let setFileScore = this.fileScore ; // 重设分
const regex = /^(?:[0-9]+)?(?:\.[0-9]{0,2})?$/; // 只能输入俩位小数
if(!regex.test(setFileScore)){
this.fileScore = Math.floor(setFileScore * 100) / 100 //保留俩位小数不进行四舍五入
}
// 防抖 input改变
clearTimeout(this.timers);
this.timers = setTimeout(()=>{
setFileScore = this.fileScore; // 重设分
if(!setFileScore) return;
// 接口请求可以写在下方
console.log('成功...');
/* add(setFileScore).then(res=>{
}) */
},1000)//一秒钟内执行一次
}
在这个示例中,我们使用了 type="number"
v-model.number
来自动将用户的输入转换为数字。然后,我们添加了一个 @input
事件监听器,该监听器会在用户每次输入时调用 onInput
方法。这个方法会检查当前输入值是否超过了 maxValue
,如果超过了,就会将 onInput
的值设置为 maxValue
。