要注意的是Vue會再mounted渲染模板上去,所以別再created時去呼叫DOM
<template>
<div id="reader"></div>
</template>
<script>
import {Html5Qrcode, Html5QrcodeScanType, Html5QrcodeSupportedFormats} from "html5-qrcode"
export default {
data() {
return {
scanner: null,
}
},
methods: {
/**
* Close QRCode
*/
close() {
if (this.scanner) {
this.scanner.stop()
}
},
/**
* Open QRCode
*/
open() {
this.scanner = new Html5Qrcode("reader")
this.scanner.start(this.selectDevice, {
formatsToSupport: [
Html5QrcodeSupportedFormats.QR_CODE,
],
supportedScanTypes: [
Html5QrcodeScanType.SCAN_TYPE_CAMERA
],
fps: 10,
aspectRatio: 1.777778,
qrbox: {
width: 250,
height: 250
},
},
(decodedText, decodedResult) => {
this.stop()
},
(errorMessage, error) => {
}
)
}
},
mounted() {
this.open()
}
}
</script>