vue实现扫描二维码
使用 vue-qrcode-reader 实现二维码扫描
安装 vue-qrcode-reader 库
npm install vue-qrcode-reader
在 Vue 组件中引入并使用
<template>
<div>
<qrcode-stream @decode="onDecode" @init="onInit" />
<p v-if="error">{{ error }}</p>
<p v-if="result">扫描结果: {{ result }}</p>
</div>
</template>
<script>
import { QrcodeStream } from 'vue-qrcode-reader'
export default {
components: { QrcodeStream },
data() {
return {
result: '',
error: ''
}
},
methods: {
onDecode(result) {
this.result = result
},
async onInit(promise) {
try {
await promise
} catch (error) {
if (error.name === 'NotAllowedError') {
this.error = "请授予相机访问权限"
} else if (error.name === 'NotFoundError') {
this.error = "未检测到摄像头设备"
} else {
this.error = error.message
}
}
}
}
}
</script>
使用 Html5Qrcode 实现二维码扫描
安装 html5-qrcode 库
npm install html5-qrcode
Vue 组件实现
<template>
<div>
<div id="qr-reader" style="width: 300px"></div>
<p v-if="result">扫描结果: {{ result }}</p>
</div>
</template>
<script>
import { Html5Qrcode } from 'html5-qrcode'
export default {
data() {
return {
result: '',
html5QrCode: null
}
},
mounted() {
this.html5QrCode = new Html5Qrcode("qr-reader")
const config = { fps: 10, qrbox: 250 }
this.html5QrCode.start(
{ facingMode: "environment" },
config,
this.onScanSuccess,
this.onScanError
).catch(err => {
console.error("无法启动扫描器:", err)
})
},
beforeDestroy() {
if (this.html5QrCode && this.html5QrCode.isScanning) {
this.html5QrCode.stop()
}
},
methods: {
onScanSuccess(decodedText) {
this.result = decodedText
},
onScanError(errorMessage) {
console.log(errorMessage)
}
}
}
</script>
注意事项
确保在 HTTPS 环境下测试,大多数现代浏览器要求安全上下文才能访问摄像头

移动端适配需要考虑横竖屏切换时的布局调整
扫描区域大小需要根据实际设备调整,过大可能导致性能问题
处理权限拒绝情况,提供友好的用户引导

扫描结果可能需要验证或过滤,防止恶意内容
扩展功能
添加扫描成功后的声音提示
playBeep() {
const audio = new Audio('beep.mp3')
audio.play()
}
添加扫描框自定义样式
#qr-reader {
border: 2px solid #42b983;
border-radius: 8px;
}
添加多摄像头切换功能
switchCamera() {
this.html5QrCode.getCameras().then(devices => {
if (devices && devices.length > 1) {
const newCameraId = devices.find(device =>
device.id !== this.currentCameraId
).id
this.html5QrCode.stop()
this.startScanner(newCameraId)
}
})
}






