Skip to content
On this page

Scan Same QR Code More Than Once

You might have noticed that scanning the same QR code again doesn't work. The thing is when a QR code is in the view of your the camera it's decoded multiple times a second. You don't want to be flooded with decode events that often though. That's why the last decoded QR code is "cached" and an event is only emitted, when the decoded content changes.

However this cache is reset when you change the camera prop. We can exploit that to scan same QR codes multiple times in a row.

Source

vue
<template>
  <div>
    <p class="decode-result">
      Last result: <b>{{ result }}</b>
    </p>

    <qrcode-stream :camera="camera" @decode="onDecode" @init="onInit">
      <div v-show="showScanConfirmation" class="scan-confirmation">
        <img :src="withBase('/checkmark.svg')" alt="Checkmark" width="128" />
      </div>
    </qrcode-stream>
  </div>
</template>

<script>
import { withBase } from 'vitepress'

import { QrcodeStream } from '../../../../src'

export default {
  components: { QrcodeStream },

  data() {
    return {
      camera: 'auto',
      result: null,
      showScanConfirmation: false
    }
  },

  methods: {
    async onInit(promise) {
      try {
        await promise
      } catch (e) {
        console.error(e)
      } finally {
        this.showScanConfirmation = this.camera === 'off'
      }
    },

    async onDecode(content) {
      this.result = content

      this.pause()
      await this.timeout(500)
      this.unpause()
    },

    unpause() {
      this.camera = 'auto'
    },

    pause() {
      this.camera = 'off'
    },

    timeout(ms) {
      return new Promise((resolve) => {
        window.setTimeout(resolve, ms)
      })
    },

    withBase
  }
}
</script>

<style scoped>
.scan-confirmation {
  position: absolute;
  width: 100%;
  height: 100%;

  background-color: rgba(255, 255, 255, 0.8);

  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
}
</style>

Released under the MIT License.