vue实现扫描二维码
实现扫描二维码的步骤
安装依赖库
使用 vue-qrcode-reader 库实现二维码扫描功能。通过 npm 或 yarn 安装:
npm install vue-qrcode-reader
# 或
yarn add vue-qrcode-reader
引入组件
在 Vue 组件中引入 QrcodeStream 和 QrcodeDropZone:
import { QrcodeStream, QrcodeDropZone } from 'vue-qrcode-reader'
添加组件模板 在模板中添加摄像头扫描区域和拖放区域:
<template>
<div>
<qrcode-stream @decode="onDecode"></qrcode-stream>
<qrcode-drop-zone @decode="onDecode">
<div>拖放二维码图片到这里</div>
</qrcode-drop-zone>
</div>
</template>
处理扫描结果
在 methods 中定义 onDecode 方法处理扫描结果:
methods: {
onDecode(decodedString) {
console.log('扫描结果:', decodedString)
alert(decodedString)
}
}
处理摄像头权限问题
检查摄像头状态
通过 @init 事件处理摄像头初始化状态:
<qrcode-stream @init="onInit" @decode="onDecode"></qrcode-stream>
处理初始化逻辑 在 methods 中添加错误处理:
async onInit(promise) {
try {
await promise
} catch (error) {
if (error.name === 'NotAllowedError') {
alert('用户拒绝了摄像头访问权限')
} else if (error.name === 'NotFoundError') {
alert('没有找到摄像头设备')
} else {
alert('摄像头初始化错误')
}
}
}
自定义样式和功能
添加扫描框样式 通过 CSS 自定义扫描框外观:
.qrcode-stream-wrapper {
border: 2px dashed #ccc;
border-radius: 8px;
max-width: 500px;
margin: 0 auto;
}
添加开关控制 在模板中添加摄像头开关按钮:
<button @click="toggleCamera">
{{ cameraActive ? '关闭摄像头' : '打开摄像头' }}
</button>
<qrcode-stream
v-if="cameraActive"
@decode="onDecode"
></qrcode-stream>
实现开关逻辑 在 data 和 methods 中添加控制逻辑:
data() {
return {
cameraActive: false
}
},
methods: {
toggleCamera() {
this.cameraActive = !this.cameraActive
}
}
处理移动端兼容性
添加全屏模式 通过 CSS 确保移动端显示正常:
.qrcode-stream-wrapper {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
}
处理横竖屏切换 监听 orientationchange 事件:
mounted() {
window.addEventListener('orientationchange', this.handleOrientationChange)
},
beforeDestroy() {
window.removeEventListener('orientationchange', this.handleOrientationChange)
},
methods: {
handleOrientationChange() {
// 重新初始化摄像头
this.cameraActive = false
this.$nextTick(() => {
this.cameraActive = true
})
}
}






