1.下载依赖包 serialport
npm i serialport
2.创建文件code-gun.js
var { SerialPort } = require("serialport"); // 串口列表 SerialPort.list() .then((ports) => { ports.forEach((port) => { console.log(port); }); }) .catch((err) => { console.error("无法获取串口列表", err); }); const codeGun = { entity: null, isOpen: false, error: null, data: null, }; codeGun.init = function (option, callback) { codeGun.entity && typeof codeGun.entity.close === "function" && codeGun.entity.close(); codeGun.entity = new SerialPort(option); console.log(codeGun.entity) //连接串口后进行写入指令操作 codeGun.entity.open(function (err) { if (!err) { console.log("扫码枪连接ok"); codeGun.isOpen = codeGun.entity.isOpen; } else { console.log("扫码枪连接失败!"); console.log(err); } }); // close codeGun.entity.on("close", function () { codeGun.isOpen = codeGun.entity.isOpen; }); // //指令监听 codeGun.entity.on("data", function (data) { let str = new String(data); console.log(str) codeGun.data = str.toString(); typeof callback === "function" && callback(); }); // //错误监听 codeGun.entity.on("error", function (error) { console.log("error: " + error); }); return codeGun; }; codeGun.close = function () { codeGun.isOpen = false; codeGun.entity && codeGun.entity.close(); }; export default codeGun;
3.App.vue 初始化
import codeGun from "@/utils/code-gun" data(){ return{ codeScanGun: { data: null, isOpen: false, timer:null, } } }, watch: { "codeScanGun.data": { handler: function(val) { if(val) { // 设置当前focus的input元素的值 let activeElement = document.activeElement; if(activeElement.tagName.toUpperCase() === 'INPUT') { activeElement.value = val // 手动触发input事件,实现数据绑定 let event = new InputEvent('input', { bubbles: true }) activeElement.dispatchEvent(event); } this.$nextTick(() => { // 重置扫码枪的值 this.codeScanGun.data = "" }) } } }, "codeScanGun.isOpen": { handler: function(val) { if(!val) { console.log("扫码枪断开连接!") this.timer && clearInterval(this.timer) this.timer = setInterval(()=>{ this.initSMQ() },2000) }else{ this.timer && clearInterval(this.timer) } } } }, created(){ this.codeScanGun = codeGun.init({ path:"com1",//串口号 baudRate:9600,//波特率 autoOpen:false }); },
标签:codeGun,function,扫码,console,log,entity,vue2,串口,data From: https://www.cnblogs.com/daifuchao/p/18087001