js版

//引入jq
//调扫码枪
$(function(){
    initScannerModule();
}) 
  function initScannerModule(){
       var code = "";
       var lastTime,nextTime;
       var lastCode,nextCode;
   
       document.onkeypress = function(e) {
           nextCode = e.which;
           nextTime = new Date().getTime();
   
           if(lastCode != null && lastTime != null && nextTime - lastTime <= 30) {
               code += String.fromCharCode(lastCode); 
           } else if(lastCode != null && lastTime != null && nextTime - lastTime > 100){
               code = "";
           }
   
           lastCode = nextCode;
           lastTime = nextTime;
       }
   
       this.onkeypress = function(e){
           if(e.which == 13){
   
               //2.获取到条形码 code
               console.log(code);



//							
               //3.根据条形码处理相关业务
   
              
//             code = "";
           }
       } 
  }

vue版

<template>
  <div class=''>
      扫描
  </div>
</template>

<script>
export default {
  name: 'sao',
  props: { }, // 父传子
  data () { // 定义数据项
    return { }
  },
  computed: { }, // 计算属性
  components: { }, // 接收子组件
    created() {
    window.document.onkeypress = (e) => {
      if (window.event) { // IE
        this.nextCode = e.keyCode
      } else if (e.which) { // Netscape/Firefox/Opera
        this.nextCode = e.which
      }

      if (e.which === 13) { // 键盘回车事件
        if (this.code.length < 3) return // 扫码枪的速度很快,手动输入的时间不会让code的长度大于2,所以这里不会对扫码枪有效
        console.log('扫码结束。')
        console.log('条形码:', this.code)
        this.parseQRCode(this.code) // 获取到扫码枪输入的内容,做别的操作
        this.lastCode = ''
        this.lastTime = ''
        return
      }

      this.nextTime = new Date().getTime()
      if (!this.lastTime && !this.lastCode) {
        this.code = '' // 清空上次的条形码
        this.code += e.key
        console.log('扫码开始---', this.code)
      }
      if (this.lastCode && this.lastTime && this.nextTime - this.lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
        this.code = e.key
        console.log('防止首字缺失。。。', this.code)
      } else if (this.lastCode && this.lastTime) {
        this.code += e.key
        console.log('扫码中。。。', this.code)
      }
      this.lastCode = this.nextCode
      this.lastTime = this.nextTime
    }
  },
  methods: {
    parseQRCode(code) {
      if (code.length === 13) {
        // 处理自己的逻辑
        this.$emit('barCode', code) //通知父组件
      } else if (code.length === 23) {
        console.log('B类条码:' + code)
      } else if (code.length === 0) {
        console.log('请输入条码!')
      } else {
        alert('条码不合法:' + code)
      }
      this.codeValue = code
    }
  }
}

</script>

<style scoped lang='less'></style>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐