原理
扫码枪本质就是一个快速输入+回车(注意:扫码输入法要设置英文,不然会乱码)
全局安装
import scanner from './install';
Vue.use(scanner);
使用
export default {
data () {
return {
items:[], //扫码结果
isStart:false //是否开启扫码
}
},
mounted(){
this.startScannerHandler();
},
methods:{
startScannerHandler(){
if(!this.isStart){
this._scanner=this.$scanner({callback:v=>{
this.items.push(v);
}});
}else{
this._scanner.cancel();
}
this.isStart=!this.isStart;
}
}
}
创建install.js
export default {
install(Vue) {
Vue.prototype.$scanner = function (options) {
var _this = this;
if (_this._callback) {
return;
}
var opt = Object.assign({
delay: 1000, // 时间太短会还没输入完成,根据测试情况修改
endChar: 'Enter',
callback: null
}, options)
var fn = {
cancel: function () {
if (_this._callback)
document.documentElement.removeEventListener('keypress', _this._callback);
delete _this._callback;
}
};
_this._callback = function (e) {
var result = _this._result || '';
var _start = _this._start || new Date();
var now = new Date();
if ((now.getTime() - _start.getTime()) > opt.delay) {
_start = now;
result = '';
}
var keyVal = `${String.fromCharCode(e.which)}`;
if (e.key == opt.endChar) {
_this._result = '';
opt.callback && opt.callback(result);
return;
}
result += keyVal;
_this._result = result;
_this._start = _start;
};
document.documentElement.addEventListener('keypress', _this._callback);
return fn;
};
}
};
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/DacingCode/article/details/138714788