vue实现扫码
Vue 实现扫码功能的方法
使用 vue-qrcode-reader 库
安装依赖库:
npm install vue-qrcode-reader
在 Vue 组件中引入并使用:

<template>
<div>
<qrcode-stream @decode="onDecode"></qrcode-stream>
<p>扫描结果: {{ result }}</p>
</div>
</template>
<script>
import { QrcodeStream } from 'vue-qrcode-reader'
export default {
components: { QrcodeStream },
data() {
return {
result: ''
}
},
methods: {
onDecode(decodedString) {
this.result = decodedString
}
}
}
</script>
使用 html5-qrcode 库
安装依赖:
npm install html5-qrcode
实现代码:

<template>
<div>
<div id="qr-reader" style="width: 500px"></div>
<p>扫描结果: {{ 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,
(decodedText) => {
this.result = decodedText
},
(errorMessage) => {
console.log(errorMessage)
}
)
},
beforeDestroy() {
if (this.html5QrCode && this.html5QrCode.isScanning) {
this.html5QrCode.stop()
}
}
}
</script>
使用原生 API 实现
通过浏览器原生 API 访问摄像头:
<template>
<div>
<video ref="video" autoplay playsinline></video>
<canvas ref="canvas" style="display: none;"></canvas>
<p>扫描结果: {{ result }}</p>
</div>
</template>
<script>
export default {
data() {
return {
result: '',
mediaStream: null
}
},
methods: {
async initCamera() {
try {
this.mediaStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' }
})
this.$refs.video.srcObject = this.mediaStream
} catch (err) {
console.error('摄像头访问失败:', err)
}
},
scanQR() {
const canvas = this.$refs.canvas
const video = this.$refs.video
const context = canvas.getContext('2d')
canvas.width = video.videoWidth
canvas.height = video.videoHeight
context.drawImage(video, 0, 0, canvas.width, canvas.height)
try {
const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
const code = jsQR(imageData.data, imageData.width, imageData.height)
if (code) {
this.result = code.data
}
} catch (e) {
console.log(e)
}
requestAnimationFrame(this.scanQR)
}
},
mounted() {
this.initCamera()
this.scanQR()
},
beforeDestroy() {
if (this.mediaStream) {
this.mediaStream.getTracks().forEach(track => track.stop())
}
}
}
</script>
移动端优化建议
对于移动端设备,建议添加以下优化:
- 设置合适的视频尺寸和扫描框大小
- 添加权限请求处理
- 考虑横竖屏适配问题
- 添加扫描成功后的反馈提示
注意事项
- 需要在 HTTPS 环境下或 localhost 才能正常使用摄像头
- 首次使用需要用户授权摄像头权限
- 不同浏览器对摄像头的支持程度可能不同
- 生产环境建议使用成熟的扫码库而非原生实现
以上方法可以根据项目需求选择适合的方案,第三方库通常提供更好的兼容性和功能支持。






