1.需在手机或者模拟器中测试,以下代码直接粘贴复制即可,
<template>
<div class="scan">
<div id="bcid">
<div style="height:40%"></div>
</div>
</div>
</template>
<script type='text/ecmascript-6'>
let scan = null;
export default {
data() {
return {
codeUrl: '',
}
},
destroyed(){// 实例销毁后关闭扫描控件
let _this = this;
_this.closeScan();
},
mounted(){// 实例挂载时创建扫描控件
let _this = this;
setTimeout(()=>{
_this.startRecognize();
},1000);
},
methods: {
//创建扫描控件
startRecognize() {
let _this = this;
if (!window.plus) return;
scan = new plus.barcode.Barcode('bcid');//创建扫描控件
scan.onmarked = onmarked;
_this.startScan();//开始扫描
function onmarked(type, result, file) {
switch (type) {
case plus.barcode.QR:// 二维码
type = 'QR';
break;
case plus.barcode.EAN13:// 条形码标准版
type = 'EAN13';
break;
case plus.barcode.EAN8:// 条形码简版
type = 'EAN8';
break;
default:
type = '其它' + type;
break;
}
result = result.replace(/\n/g, '');
_this.codeUrl = result;// 获取扫描结果
alert(that.codeUrl);
_this.closeScan();// 得到结果后关闭控件
window.location.href = that.codeUrl;// 跳转路径
}
},
//开始扫描
startScan() {
if (!window.plus) return;
scan.start();
},
//关闭扫描
cancelScan() {
if (!window.plus) return;
scan.cancel();
},
//关闭条码识别控件
closeScan() {
if (!window.plus) return;
scan.close();
},
}
}
</script>
<style lang="stylus" scoped>
.scan{
height: 100%;
#bcid{
width: 100%;
height: 100%;
text-align: center;
color: #fff;
background :#cccccc;
}
}
</style>
tips:mounted函数调取创建控件方法时,直接调用会失败,当延时后才会成功