Vue.js working with input from a barcode scanner

Viewed 2024

I've stumbled upon an interesting case in a web-module, designed for both user- and machine-input (via a barcode scanner). Here is the code from Vue's module:

<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();
        }
    })
},

The scanner can trigger keyup.enter at the end, but it inputs the barcode so fast, that the model does not update. Only by adding 10 ms delay after the input (custom setting in the scanner) and then sending keyup.enter, everything is working as expected.

The big question is: how can I "slow down" scanner's input instead of tweaking the scanner settings (obviously not convenient for other cases)?

Best regards

2 Answers

Try calling it in 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();
      }
    })
  });
}

I would give nextTick a try

You could use it like this:

parseBarcode(){
    // validates barcode (string)
    myAPI.getBarcodeId(this.barcode).then(({data}) => {
        if (data.errors) {
            this.showError()
        } else {
            this.$nextTick(() => {
               this.focusBarcodeInput();
         });
        }
    })
},
Related