1. 安装ZXing.js
首先,你需要将ZXing.js库引入到你的Vue项目中。你可以通过CDN方式引入,也可以通过npm安装。这里我们使用CDN方式。
2. 创建扫码组件
创建一个新的Vue组件,例如 QRCodeScanner.vue
,并在其中封装ZXing.js的扫码功能
<template>
<div>
<video ref="video" width="640" height="480" autoplay></video>
<canvas ref="canvas" style="display: none;"></canvas>
</div>
</template>
<script>
export default {
name: 'QRCodeScanner',
props: {
onResult: {
type: Function,
required: true
}
},
mounted() {
this.initScanner();
},
methods: {
initScanner() {
const video = this.$refs.video;
const canvas = this.$refs.canvas;
const context = canvas.getContext('2d');
// Get user media for video stream
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
video.srcObject = stream;
video.play();
const scanner = new window.ZXing.BrowserQRCodeReader();
scanner.decodeFromVideoDevice(video, canvas, (result, error) => {
if (result) {
this.onResult(result.text);
}
if (error) {
console.error(error);
}
});
})
.catch(error => {
console.error('Error accessing user media:', error);
});
}
}
};
</script>
<style scoped>
video {
border: 1px solid black;
}
</style>
3. 使用扫码组件
<template>
<div>
<h1>QR Code Scanner</h1>
<QRCodeScanner @result="handleScanResult" />
<p v-if="scanResult">Scan Result: {{ scanResult }}</p>
</div>
</template>
<script>
import QRCodeScanner from './QRCodeScanner.vue';
export default {
name: 'App',
components: {
QRCodeScanner
},
data() {
return {
scanResult: ''
};
},
methods: {
handleScanResult(result) {
this.scanResult = result;
console.log('Scan Result:', result);
}
}
};
</script>
<style>
body {
font-family: Arial, sans-serif;
}
</style>
4. 引入ZXing.js库
在你的 index.html
文件中,通过CDN引入ZXing.js库。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue QR Code Scanner</title>
<script src="https://cdn.jsdelivr.net/npm/zxing-js/library/umd/index.min.js"></script>
</head>
<body>
<div id="app"></div>
<script src="/path/to/your/built/app.js"></script>
</body>
</html>