项目中使用了keep-alive缓存, 扫描事件写在了activated里面了 这样每次进入页面都会开启扫描。
代码很简单,就直接贴上来了
<template>
<div class="qr-code">
<div style="background: black;position: fixed;top: 50px;left: 0;right: 0;bottom: 0;">
<div id="bcid"></div>
</div>
</div>
</template>
<script type='text/ecmascript-6'>
let scan = null;
export default {
data() {
return {
codeUrl: '',
}
},
created(){
},
activated() {
this.startRecognize();
},
mounted(){
},
methods: {
startRecognize() {
let _this = this;
if (!window.plus) return;
//创建扫描控件
scan = new plus.barcode.Barcode('bcid',
[plus.barcode.QR, plus.barcode.EAN8, plus.barcode.EAN13],
{ frameColor: "#00FF00", scanbarColor: "#00FF00" });
//开始扫描
scan.start();
scan.onmarked = onmarked;
function onmarked(type, result, file) {
let codes = result.split(":");
let key = codes[0];
let value = codes[1];
switch (type) {
case plus.barcode.QR:
type = 'QR';
break;
case plus.barcode.EAN13:
type = 'EAN13';
break;
case plus.barcode.EAN8:
type = 'EAN8';
break;
default:
_this.$layer.open({time:3,skin:'msg',content:'未能识别二维码'});
scan.start();
break;
}
result = result.replace(/\n/g, '');
_this.codeUrl = result;
if(_this.$route.params.type == 'homeIndex'){
_this.$router.push('/home')
}else if(_this.$route.params.type == 'transferAccounts'){
_this.codeResult.$emit('result',result);
_this.$router.push('/transferAccounts')
}
}
}
},
beforeDestroy() {
if(scan){
//关闭扫描控件
scan.close();
}
},
computed:{
}
}
</script>
<style lang="css">
.qr-code{
background-color: #FAF8F5;
}
#bcid {
width: 100%;
position: absolute;
left: 0;
right: 0;
top: 50px;
bottom:3rem;
text-align: center;
color: #fff;
background: #000;
}
</style>
这个后面做了测试,不能开启扫描。一直没找的原因所在,想想会不会是keep-alive的原因,设置了keepAlive:false,再将activated里的方法放到created中。 结果就可以了。
2019/02/11号 补充:
项目添加了很多新页面,从某一个页面跳转到扫描二维码页面不会开启扫描(其他页面都可以)并且返回上个页面后会自动横屏。最后加了一个setTimeout,可以了。具体原因不是很清楚
mounted(){
setTimeout(() => {
this.startRecognize();
},500)
},