uniapp做pda扫码有两种方式,
第一种利用输入框(input)做,体验感不好
第二种利用pda系统的系统广播做,能即时刷新数据
第一
选择系统中广播模式
或者
两种手机型号不一样
第二
在components中加公共组件直接调用
scan-code.vue
<template>
<view class="content"></view>
</template>
<script>
var main,receiver,filter;
var _codeQueryTag = false;
export default {
data() {
return {
scanCode: ''
}
},
created: function (option) {
this.initScan()
this.startScan();
},
onHide:function(){
this.stopScan();
},
destroyed:function(){
/*页面退出时一定要卸载监听,否则下次进来时会重复,造成扫一次出2个以上的结果*/
this.stopScan();
},
methods: {
initScan() {
let _this = this;
main = plus.android.runtimeMainActivity();//获取activity
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
filter = new IntentFilter();
filter.addAction("com.scanner.broadcast"); // 换你的广播动作 (条码广播名)
receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver',{
onReceive : function(context, intent) {
plus.android.importClass(intent);
let code = intent.getStringExtra("data");// 换你的广播标签 (条码键值名)
_this.queryCode(code);
}});
},
startScan(){
main.registerReceiver(receiver,filter);
},
stopScan(){
main.unregisterReceiver(receiver);
},
queryCode: function(code){
//防重复
if(_codeQueryTag)return false;
_codeQueryTag = true;
setTimeout(function(){
_codeQueryTag = false;
},150);
var id = code
uni.$emit('scancodedate',{code:id})
}
}
}
</script>
<style>
page {
background-color: #efeff4;
}
.content {
text-align: center;
}
</style>
在需要扫码的组件中直接调用
<template>
<!-- 自己的组件内容 -->
<!-- 引用组件 -->
<scan-code></scan-code>
</template>
<script>
var main,receiver,filter;
var _codeQueryTag = false;
export default {
data() {
return {
scanCode: ''
}
},
onLoad: function (option) {
uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
uni.$on('scancodedate',function(data){
console.log(data.code)
})
},
}
</script>
<style>
</style>
在退出页面或者跳转页面时
一定要清除事件 uni.$off('scancodedate')