【仅在 https 或 localhost 等安全上下文中支持摄像头访问】,待解决
一、下载依赖
npm i html5-qrcode
二、引入
import {Html5Qrcode} from "html5-qrcode";
二维码扫描父组件
<template>
<BarScan ref="qrcode" @ok="getResult" @err="geterror"></BarScan>
</template>
<script>
import BarScan from './components/qrcode.vue'
export default {
components: {
BarScan
},
methods: {
getResult(result) {
this.$toast(result)
this.$router.push({name:'sports_sign',query:{id:result}})
},
geterror(e) {
this.$toast(e)
},
}
}
</script>
子组件
<template>
<div class="qrcode">
<div id="reader"></div>
</div>
</template>
<script>
import {Html5Qrcode} from "html5-qrcode";
export default {
data(){
return {
html5QrCode:null,
}
},
created() {
this.getCameras()
navigator.mediaDevices.getUserMedia(constraints)
.then(function (stream) {
})
.catch(function (err) {
});
},
beforeDestroy() {
this.stop();
},
methods: {
getCameras() {
Html5Qrcode.getCameras()
.then((devices) => {
if (devices && devices.length) {
this.html5QrCode = new Html5Qrcode("reader");
this.start();
}
})
.catch((err) => {
this.html5QrCode = new Html5Qrcode("reader");
this.error = "您需要授予相机访问权限"
this.$emit("err", this.error)
});
},
start() {
this.html5QrCode
.start(
{facingMode: "environment"},
{
fps: 2,
qrbox: {width: 250, height: 250},
},
(decodedText, decodedResult) => {
this.$emit("ok", decodedText)
}
)
.catch((err) => {
this.$emit("err", err)
});
},
stop() {
this.html5QrCode.stop().then((ignore) => {
console.log("QR Code scanning stopped.");
})
.catch((err) => {
console.log("Unable to stop scanning.");
});
},
}
}
</script>
<style lang="scss" scoped>
.qrcode {
position: relative;
height: 100vh;
width: 100vw;
background: rgba($color: #000000, $alpha: 0.48);
}
#reader {
top: 50%;
left: 0;
transform: translateY(-50%);
}
</style>