首先根目录下创建index.html,在其中引入js库
<script src="https://unpkg.com/html5-qrcode"></script>
其次在manifest.json中引入index.html
"h5" : {
"title" : "xxxx",
"domain" : "",
"router" : {
"mode" : "history"
},
// 这里引入html
"template" : "index.html",
"optimization" : {
"treeShaking" : {
"enable" : true
}
}
}
最后在页面中调用
<button @click="getCameras" type="warn" class="margin-top" >扫一扫</button>
展示扫码界面
<view class="cu-modal" :class="modalName == 'scanModal' ? 'show' : ''">
<view class="cu-dialog">
<view class="cu-bar bg-white justify-end">
<view class="content">开始扫码</view>
<view class="action" @click="hideScanModal">
<view class="cuIcon-close text-red"></view>
</view>
</view>
<view class="padding-xl">
<scroll-view scroll-y class="page">
<div id="qr-reader" style="height: 250px;"></div>
</scroll-view>
</view>
</view>
</view>
//关闭扫码窗口
hideScanModal() {
this.modalName = null;
this.stop();
},
getCameras() {
Html5Qrcode.getCameras()
.then((devices) => {
/**
* devices would be an array of objects of type:
* { id: "id", label: "label" }
*/
if (devices && devices.length) {
if (devices.length > 1) {
this.cameraId = devices[1].id;
} else {
this.cameraId = devices[0].id;
}
console.log(this.cameraId, "cameraId");
this.start();
// .. use this to start scanning.
}
})
.catch((err) => {
// handle err
});
},
//扫码成功
getCode(qrCodeMessage) {
console.log('qrCodeMessage', qrCodeMessage)
let dzbm = qrCodeMessage.split('?')[1].split('&')[0].split('=')[1]
console.log("dzbm,", dzbm)
this.modalName = null;
if (dzbm) {
}
return
let codeId = getUrlParamFromUrl(qrCodeMessage, "id");
console.log(codeId);
if (codeId) {
this.$router.push({
path: "/home",
query: {
codeId: codeId
}
});
} else {
Dialog.confirm({
title: "提示",
message: "二维码错误,请重新扫码",
})
.then(() => {
this.start();
})
.catch(() => {
// on cancel
});
}
},
stop() {
this.html5QrCode
.stop()
.then((ignore) => {
// QR Code scanning is stopped.
console.log("QR Code scanning stopped.");
this.show = false;
})
.catch((err) => {
// Stop failed, handle it.
console.log("Unable to stop scanning.");
});
},
start() {
this.show = true;
this.modalName = 'scanModal'
this.html5QrCode = new Html5Qrcode("qr-reader");
this.html5QrCode
.start(
this.cameraId, // retreived in the previous step.
{
fps: 10, // sets the framerate to 10 frame per second
qrbox: 250, // sets only 250 X 250 region of viewfinder to
// scannable, rest shaded.
},
(qrCodeMessage) => {
// do something when code is read. For example:
if (qrCodeMessage) {
this.stop();
this.getCode(qrCodeMessage);
}
},
(errorMessage) => {
// parse error, ideally ignore it. For example:
console.log(`QR Code no longer in front of camera.`);
}
)
.catch((err) => {
// Start failed, handle it. For example,
console.log(`Unable to start scanning, error: ${err}`);
});
},