Skip to content

Commit

Permalink
Add qrcode scanner
Browse files Browse the repository at this point in the history
  • Loading branch information
yuto0226 committed Aug 6, 2024
1 parent 68bd536 commit 314ec11
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 3 deletions.
84 changes: 84 additions & 0 deletions src/components/QRcodeReader.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<template>
<div class="card">
<div class="card-body">
<div class="ratio ratio-1x1" id="qr-reader" v-if="!scanComplete" width="500"></div>
</div>
<div v-if="result">掃描結果: {{ result }}</div>
</div>
<div class="d-grid col-6 mx-auto my-4">
<button :class="btn_class" type="button" @click="toggleCamera">{{ btn_text }}</button>
</div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Html5Qrcode } from "html5-qrcode"
const scanComplete = ref(false)
const result = ref('')
let html5QrCode = null
const emit = defineEmits(['scan-success'])
const initScanner = () => {
try {
html5QrCode = new Html5Qrcode("qr-reader")
const config = { fps: 10, qrbox: { width: 250, height: 250 } }
html5QrCode.start(
{ facingMode: "environment" },
config,
onScanSuccess,
onScanFailure
)
} catch (error) {
console.log('init scanner failed: ' + error)
}
}
const onScanSuccess = (decodedText) => {
result.value = decodedText
// 可以在這裡處理掃描成功後的邏輯
emit('scan-success', decodedText)
}
const onScanFailure = (error) => {
// 處理掃描失敗的情況
console.warn(`QR Code scanning failed: ${error}`)
}
onMounted(() => {
toggleCamera();
});
onBeforeUnmount(() => {
stopScanner();
});
const stopScanner = async () => {
if (html5QrCode) {
try {
await html5QrCode.stop()
} catch (error) {
console.error("Failed to stop scanner:", error)
}
}
}
const camera_is_opened = ref(false);
const btn_class = ref('btn btn-primary');
const btn_text = ref('關閉相機');
const toggleCamera = async () => {
camera_is_opened.value = !camera_is_opened.value;
if (camera_is_opened.value) {
initScanner();
btn_class.value = 'btn btn-danger';
btn_text.value = '關閉相機';
} else {
stopScanner();
btn_class.value = 'btn btn-primary';
btn_text.value = '開啟相機';
}
}
</script>
22 changes: 19 additions & 3 deletions src/views/ScanView.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
<script setup></script>
<script setup>
import { ref } from 'vue';
import QRcodeReader from '@/components/QRcodeReader.vue';
const account = ref('');
const handleScanSuccess = (data) => {
account.value = data
pageMsg.value = '掃描成功';
}
const pageMsg = ref('');
const isError = ref(false);
</script>
<template>
<div>
<h1>Scan</h1>

<h1 class="mb-4">Scan</h1>
<div v-if="pageMsg" class="mt-3" :class="['alert', isError ? 'alert-danger' : 'alert-success']" role="alert">
{{ pageMsg }}
</div>
<QRcodeReader @scan-success="handleScanSuccess" />
</div>
</template>

0 comments on commit 314ec11

Please sign in to comment.