Vuejs keyup,条码读取13次以上

Vuejs keyup, barcode read more than 13 times

我正在使用条形码 reader,即使我等待 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);
        }
    }
});