在uniapp内,使用5+ API实现扫一扫
首先需要准备两个页面,这里是首页,和负责扫一扫功能逻辑的页面
首页:这里首页代码特别简单,只需要跳转到扫一扫页面,并获取扫一扫页面返回的值。
// 负责跳转到扫一扫页面
<button @click="goBack('/pages/login/scan')">扫一扫开启</button>
//负责接收从扫一扫页面传回的扫描结果:option.result
onLoad(option) {
if(option.result){
uni.showToast({
icon:'none',
mask:true,
title: option.result,
});
}
uni.setStorageSync('first_falg', true);//是否第一次进入APP,true不是,跳过引导页
},
扫一扫页面:
data() {
return {
barcode:null,//创建扫一扫对象
result:'',//扫描结果
setFlash:false,//是否开启闪光灯
}
},
onLoad() {
let _this = this;
_this.barcode = null;
if(!_this.barcode){
// 创建Barcode扫码控件,此方法创建扫码识别控件并不会显示在页面中,需要调用plus.webview.Webview窗口对象的append方法将其添加到Webview窗口中才能显示
_this.barcode = plus.barcode.create('barcode', [plus.barcode.QR], {
top:'44px',
left:'0',
width: '100%',
height: '100%',
position: 'static'
});
plus.webview.currentWebview().append(_this.barcode);
_this.barcode.onmarked = onmarked;
}
_this.barcode.start();//开启扫一扫
//获取扫描结果
function onmarked(type, result) {
_this.result = result;
var text = '未知: ';
switch(type){
case plus.barcode.QR:
text = 'QR: ';
break;
case plus.barcode.EAN13:
text = 'EAN13: ';
break;
case plus.barcode.EAN8:
text = 'EAN8: ';
break;
}
_this.barcode.cancel();//结束对摄像头获取图片数据进行条码识别操作,同时关闭摄像头的视频捕获。 结束后可调用start方法重新开始识别。
_this.barcode.close();//释放控件占用系统资源,调用close方法后控件对象将不可使用。
_this.goBack(1);//扫描成功,返回首页
}
},
methods: {
//开启闪光灯
open(){
this.setFlash = !this.setFlash
this.barcode.setFlash(this.setFlash);
},
//页面跳转
goBack(name) {
if (name == 1) {
this.barcode.cancel();//结束对摄像头获取图片数据进行条码识别操作,同时关闭摄像头的视频捕获。 结束后可调用start方法重新开始识别。
this.barcode.close();//释放控件占用系统资源,调用close方法后控件对象将不可使用。
if(this.result){
uni.reLaunch({
url: '/pages/login/login?result='+this.result,
animationType: 'pop-in',
animationDuration: 300
})
}else{
uni.navigateBack({
delta: name,
animationType: 'pop-out',
animationDuration: 300
});
}
} else {
uni.navigateTo({
url: name,
animationType: 'pop-in',
animationDuration: 300
})
}
},
},