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>
使用 html5-qrcode 库
安装 html5-qrcode 库:
npm install html5-qrcode
在 Vue 组件中实现扫码:
<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: ''
}
},
mounted() {
const html5Qrcode = new Html5Qrcode('qr-reader')
html5Qrcode.start(
{ facingMode: 'environment' },
{ fps: 10, qrbox: 250 },
(decodedText) => {
this.result = decodedText
},
(errorMessage) => {
console.error(errorMessage)
}
)
}
}
</script>
使用原生 API 实现
通过浏览器原生 API 调用摄像头并解析二维码:
<template>
<div>
<video ref="video" width="400" height="300" autoplay></video>
<canvas ref="canvas" width="400" height="300" style="display: none"></canvas>
<button @click="scanQR">开始扫描</button>
<p>扫描结果: {{ result }}</p>
</div>
</template>
<script>
export default {
data() {
return {
result: '',
interval: null
}
},
methods: {
async scanQR() {
const stream = await navigator.mediaDevices.getUserMedia({ video: true })
this.$refs.video.srcObject = stream
this.interval = setInterval(() => {
const canvas = this.$refs.canvas
const context = canvas.getContext('2d')
context.drawImage(this.$refs.video, 0, 0, canvas.width, canvas.height)
const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
// 这里需要添加二维码解析逻辑
// 可以使用第三方库如 jsQR 来解析
}, 500)
}
},
beforeDestroy() {
if (this.interval) clearInterval(this.interval)
if (this.$refs.video.srcObject) {
this.$refs.video.srcObject.getTracks().forEach(track => track.stop())
}
}
}
</script>
移动端适配
对于移动端设备,需要考虑权限请求和横竖屏适配:
<template>
<div class="scanner-container">
<qrcode-stream
@decode="onDecode"
:torch="torchActive"
@torch-compatibility="onTorchCompatibility"
></qrcode-stream>
<button @click="toggleTorch">切换闪光灯</button>
</div>
</template>
<script>
import { QrcodeStream } from 'vue-qrcode-reader'
export default {
components: { QrcodeStream },
data() {
return {
result: '',
torchActive: false,
hasTorch: false
}
},
methods: {
onDecode(decodedString) {
this.result = decodedString
},
onTorchCompatibility({ compatible }) {
this.hasTorch = compatible
},
toggleTorch() {
if (this.hasTorch) {
this.torchActive = !this.torchActive
}
}
}
}
</script>
<style>
.scanner-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
以上方法提供了从简单到复杂的多种实现方案,可以根据项目需求选择合适的方案。对于生产环境,推荐使用成熟的第三方库如 vue-qrcode-reader 或 html5-qrcode,它们已经处理了大多数兼容性和性能问题。







