vue实现 扫码
Vue 实现扫码功能的方法
在 Vue 中实现扫码功能可以通过以下几种方式完成,具体选择取决于项目需求和技术栈。
使用第三方库(如 vue-qrcode-reader)
安装 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>
使用原生 API(如 MediaDevices)
通过浏览器原生 API 调用摄像头并解析二维码:

<template>
<div>
<video ref="video" autoplay playsinline></video>
<button @click="startScan">开始扫描</button>
<p>扫描结果: {{ result }}</p>
</div>
</template>
<script>
export default {
data() {
return {
result: '',
videoStream: null
}
},
methods: {
async startScan() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: true })
this.$refs.video.srcObject = stream
this.videoStream = stream
// 这里需要添加二维码解析逻辑
} catch (error) {
console.error('Error accessing camera:', error)
}
},
stopScan() {
if (this.videoStream) {
this.videoStream.getTracks().forEach(track => track.stop())
}
}
},
beforeDestroy() {
this.stopScan()
}
}
</script>
使用 zxing-js 库进行二维码解析
安装 zxing-js:
npm install @zxing/library
结合摄像头使用的完整示例:
<template>
<div>
<video ref="video" autoplay playsinline></video>
<button @click="startScan">开始扫描</button>
<button @click="stopScan">停止扫描</button>
<p>扫描结果: {{ result }}</p>
</div>
</template>
<script>
import { BrowserQRCodeReader } from '@zxing/library'
export default {
data() {
return {
result: '',
codeReader: null,
videoStream: null
}
},
methods: {
async startScan() {
this.codeReader = new BrowserQRCodeReader()
try {
const result = await this.codeReader.decodeFromVideoDevice(
null,
this.$refs.video,
(result, error) => {
if (result) {
this.result = result.getText()
}
if (error && !(error instanceof ZXing.NotFoundException)) {
console.error(error)
}
}
)
} catch (error) {
console.error('Error starting scan:', error)
}
},
stopScan() {
if (this.codeReader) {
this.codeReader.reset()
this.codeReader = null
}
}
},
beforeDestroy() {
this.stopScan()
}
}
</script>
注意事项
- 使用摄像头功能需要 HTTPS 环境或 localhost 开发环境
- 需要用户授权摄像头权限
- 移动端浏览器可能有不同的兼容性问题
- 对于生产环境,建议使用成熟的第三方库而非原生 API
- 考虑添加错误处理和用户引导界面
以上方法可以根据项目需求选择最适合的实现方式,vue-qrcode-reader 提供了最简化的 Vue 集成方案,而 zxing-js 则提供了更底层的控制能力。






