Vuejs键盘,条形码读取超过13次



我使用的是条形码阅读器,尽管我等待了3秒钟,但它发送了很多请求。

<div id="app">
<input 
type="text"
v-on:keyup="barcode"
>
</div>

vuejs代码:

<script>
var app = new Vue({
el: '#app',
data: {},
methods: {
barcode(){
setTimeout(() => {
console.log('number of times executed');
}, 3000);
}
}
})
</script>

控制台:

number of times executed                      (17) keyup.html:26:33

我只需要一次发送请求,因为许多原因,如错误429等

谢谢你抽出时间!

了解发生了什么

  1. 扫描仪是一种外围设备,其功能类似键盘
  2. 扫描条形码后,扫描仪会将按键快速连续发送到您的机器
  3. 这导致该方法在超时后被调用13次
  4. 可以理解的是,您正在联系的端点正在发回一个错误429 - Too Many Requests

解决方案

  • 您需要等到最后一次按键后才能联系端点
  • 为超时指定一个引用,以便在下次击键时清除它
  • 在最后一次击键时,它将超时并按预期执行您的代码
var app = new Vue({
el: '#app',
data: {},
methods: {
barcode() {
// We sent a keyup event and a timer is still active
if(this.timer) {
// So we clear and null it so it doesn't contact the api
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
// contact your endpoint here
// Assuming your scanner can emit keystrokes
// within 100 milliseconds from one another
// otherwise increase this value as necessary
}, 100);
}
}
});

最新更新