首页 > 解决方案 > Vue.js 处理来自条形码扫描仪的输入

问题描述

我在 web 模块中偶然发现了一个有趣的案例,该模块专为用户和机器输入(通过条形码扫描仪)而设计。以下是 Vue 模块的代码:

<input 
    class="form-control"
    v-model="barcode"
    id="barcode-scanner"
    @keyup.enter="parseBarcode"
/>

parseBarcode(){
    // validates barcode (string)
    myAPI.getBarcodeId(this.barcode).then(({data}) => {
        if (data.errors) {
            this.showError()
        } else {
            // do some work and focus on input
            this.focusBarcodeInput();
        }
    })
},

扫描仪可以在最后触发keyup.enter,但它输入条形码的速度太快,以至于模型不会更新。只有在输入(扫描仪中的自定义设置)后添加 10 毫秒延迟然后发送keyup.enter,一切都按预期工作。

最大的问题是:我怎样才能“减慢”扫描仪的输入而不是调整扫描仪设置(对于其他情况显然不方便)?

此致

标签: javascriptvue.jsvuejs2dom-eventsbarcode

解决方案


尝试在this.$nextTick中调用它:

parseBarcode () {
  this.$nextTick(() => {
    myAPI.getBarcodeId(this.barcode).then(({data}) => {
      if (data.errors) {
        this.showError()
      } else {
        // do some work and focus on input
        this.focusBarcodeInput();
      }
    })
  });
}

推荐阅读