微信小程序给我们提供了 wx.scanCode 调起客户端进行扫码,每次扫码完都会关闭扫瞄界面,当我们遇到连续扫码的需求时,wx.scanCode就满足不了了,我们可以用 camera 组件实现扫码枪的效果。
1.微信公众平台授权摄像头
首先,我们需要用户授权 scope.camera
。登陆微信公众平台,在设置中找到「服务内容声明」,更新「用户隐私保护指引」,在「用户隐私保护指引设置」中添加「摄像头」并提交审核,审核通过后小程序中就可以正常使用camera组件了。
2.具体代码实现
<template>
<view>
<camera
mode="scanCode"
device-position="back"
flash="off"
@scancode="takeCode"
@binderror="binderror"
style="width: 100%; height: calc(100vh)"
></camera>
</view>
</template>
<script>
export default {
data() {
return {
flag: true,
};
},
onLoad() {
this.ctx = wx.createCameraContext();
},
onUnload() {
// 在此处理用户返回上一页时的逻辑,下面仅供参考
let pages = getCurrentPages();
pages[pages.length - 2].$vm.refresh();
},
methods: {
takeCode(e) {
const that = this;
if (that.flag) {
that.flag = false;
// 在此处理扫描结果或请求接口
// 最好加上定时器,防止重复提交
setTimeout(() => {
that.flag = true;
}, 1000);
}
},
error(e) {
console.log("e", e.detail);
},
// 用户不允许使用摄像头时触发
binderror() {
wx.showToast({
icon: "none",
title: "请授权摄像头",
});
setTimeout(() => {
uni.navigateBack();
}, 1000);
},
},
};
</script>