V3 快速扫码枪识别录入功能(导入即用)

1.创建扫码方法类ts

        创建一个scan.ts的文件

// scan.ts
export default class Scan {
  private barCode: string = '';
  private lastTime: number = 0;
  private timeout: number;
  private timer: NodeJS.Timeout | null = null;
  private eventHandler: (e: KeyboardEvent) => void;

  constructor(timeout = 100) {
    this.timeout = timeout;
    this.eventHandler = this.eventListenerScanCode.bind(this);
  }

  private eventListenerScanCode(e: KeyboardEvent): void {
    const currCode = e.keyCode || e.which || e.charCode;
    const currTime = new Date().getTime();

    if (this.lastTime > 0) {
      if (currTime - this.lastTime <= this.timeout) {
        this.barCode += String.fromCharCode(currCode!);
      } else {
        this.clearBarCode();
      }
    } else {
      this.barCode = String.fromCharCode(currCode!);
    }

    // console.log(currTime, "监听到的值:", this.barCode);
    this.lastTime = currTime;

    if (currCode === 13) { // Enter键
      if (this.barCode) {
        const code = this.barCode.substring(0, this.barCode.length - 1).trim(); // 去除末尾的Enter键
        if (code) {
          this.emitScan(code);
        }
      }
      this.clearBarCode();
    }

    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      if (this.lastTime) {
        this.clearBarCode();
        console.log("执行清空");
      }
      clearTimeout(this.timer);
    }, this.timeout);
  }

  private clearBarCode(): void {
    this.barCode = '';
    this.lastTime = 0;
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  }

  public start(): void {
    window.addEventListener("keypress", this.eventHandler);
  }

  public stop(): void {
    window.removeEventListener("keypress", this.eventHandler);
    this.clearBarCode();
  }

  private emitScan(code: string): void {
    this.onScanCallbacks.forEach(callback => callback(code));
  }

  private onScanCallbacks: ((code: string) => void)[] = [];

  public onScan(callback: (code: string) => void): () => void {
    this.onScanCallbacks.push(callback);

    return () => {
      this.onScanCallbacks = this.onScanCallbacks.filter(cb => cb !== callback);
    };
  }
}

2.使用

页面上直接使用,对扫码的条形码进行业务逻辑

<script lang="ts" setup>
import { onMounted, onBeforeUnmount } from 'vue';
import Scan from '@/utils/scan';

const scan = new Scan(200); // 200是扫码枪有效输入间隔毫秒

const handleScan = (code: string) => {
    console.log('Scanned code:', code);
    // 处理扫描后的逻辑
};
let removeScanListener: () => void;

onMounted(() => {
    // 开始监听扫码枪扫码并设置回调
    removeScanListener = scan.onScan(handleScan);
    scan.start();
});

onBeforeUnmount(() => {
    // 结束监听
    scan.stop();
    // 移除全局事件监听器
    if (removeScanListener) removeScanListener();
});
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值