html5-qrcode – 브라우저 바코드 스캔

By | 2026년 3월 2일
Table of Contents

html5-qrcode – 브라우저 바코드 스캔

VueJS 프로젝트에서 바코드를 스캔해서 화면에 표시하는 기능을 구현합니다.

의존성 추가

npm install html5-qrcode

컴포넌트 생성

<template>
  <div ref="scannerRef" id="qr-reader"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { Html5Qrcode } from 'html5-qrcode';

// 부모 컴포넌트로 결과를 전달하기 위한 이벤트
const emit = defineEmits(['scan-success']);

const scannerRef = ref(null);
let html5QrCode = null;

onMounted(() => {
  html5QrCode = new Html5Qrcode("qr-reader");

  const config = {
    fps: 10,
    qrbox: { width: 250, height: 100 },
    formatsToSupport: [ 10 ] // EAN-13 (Html5QrcodeSupportedFormats.EAN_13)
  };

  html5QrCode.start(
    { facingMode: "environment" },
    config,
    (decodedText) => {
      emit('scan-success', decodedText);
    },
    (errorMessage) => { /* 무시 */ }
  ).catch(err => {
    console.error("카메라 시작 실패:", err);
  });
});

// 컴포넌트가 파괴될 때 반드시 스캐너를 멈춰야 합니다!
onBeforeUnmount(async () => {
  if (html5QrCode && html5QrCode.isScanning) {
    await html5QrCode.stop();
  }
});
</script>

<style scoped>
#qr-reader {
  width: 100%;
  max-width: 500px;
}
</style>

호출 페이지 생성

<template>
  <div>
    <h1>상품 스캔</h1>
    <BarcodeScanner @scan-success="onBarcodeDetected" />
    <p v-if="barcode">인식된 코드: {{ barcode }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import BarcodeScanner from './components/BarcodeScanner.vue';

const barcode = ref('');

const onBarcodeDetected = (code) => {
  barcode.value = code;
  alert(`바코드 인식 완료: ${code}`);
};
</script>
Category: Web

답글 남기기