vue实现串口通信
使用 Vue 实现串口通信
Vue 本身是一个前端框架,无法直接操作串口(Serial Port),但可以通过以下方法间接实现串口通信功能:
通过 Web Serial API(现代浏览器支持)
Web Serial API 是浏览器提供的 API,允许网页与串口设备通信,但需要用户授权。
安装依赖(如需要):
npm install @serialport/stream
示例代码:
<template>
<div>
<button @click="requestSerialPort">连接串口</button>
<button @click="sendData">发送数据</button>
</div>
</template>
<script>
export default {
methods: {
async requestSerialPort() {
try {
const port = await navigator.serial.requestPort()
await port.open({ baudRate: 9600 })
this.serialPort = port
this.readData()
} catch (err) {
console.error('串口错误:', err)
}
},
async readData() {
const reader = this.serialPort.readable.getReader()
try {
while (true) {
const { value, done } = await reader.read()
if (done) break
console.log('接收数据:', new TextDecoder().decode(value))
}
} catch (err) {
console.error('读取错误:', err)
} finally {
reader.releaseLock()
}
},
async sendData() {
const writer = this.serialPort.writable.getWriter()
const data = new TextEncoder().encode('Hello Serial Port')
await writer.write(data)
writer.releaseLock()
}
}
}
</script>
通过 Electron 集成
对于桌面应用,可以使用 Electron 结合 Node.js 的串口库:

安装依赖:
npm install electron serialport
主进程代码(main.js):
const { app, BrowserWindow } = require('electron')
const SerialPort = require('serialport')
function createWindow() {
const win = new BrowserWindow({/* 配置 */})
win.loadFile('index.html')
const port = new SerialPort('COM3', { baudRate: 9600 })
port.on('data', data => {
win.webContents.send('serial-data', data.toString())
})
win.webContents.on('serial-send', (event, data) => {
port.write(data)
})
}
渲染进程(Vue组件):

<template>
<div>
<button @click="sendData">发送</button>
<div>接收数据: {{ receivedData }}</div>
</div>
</template>
<script>
export default {
data() {
return {
receivedData: ''
}
},
mounted() {
window.ipcRenderer.on('serial-data', (event, data) => {
this.receivedData = data
})
},
methods: {
sendData() {
window.ipcRenderer.send('serial-send', 'Hello from Vue')
}
}
}
</script>
通过后端服务中转
另一种方法是通过后端服务(如Node.js)处理串口通信,Vue前端通过WebSocket或HTTP与后端交互:
后端示例(Node.js):
const express = require('express')
const SerialPort = require('serialport')
const app = express()
const port = new SerialPort('COM3', { baudRate: 9600 })
app.use(express.json())
app.post('/send', (req, res) => {
port.write(req.body.data)
res.sendStatus(200)
})
port.on('data', data => {
// 可以通过WebSocket广播给前端
console.log('Received:', data.toString())
})
app.listen(3000)
Vue前端调用:
methods: {
sendData() {
axios.post('http://localhost:3000/send', { data: 'Hello' })
}
}
注意事项
- Web Serial API需要HTTPS环境或localhost
- 串口参数(波特率、数据位等)需与设备匹配
- 错误处理要完善,特别是断开连接的情况
- 生产环境建议使用WebSocket实现实时双向通信
选择哪种方案取决于具体应用场景和运行环境。浏览器方案适合简单应用,Electron适合桌面应用,后端中转方案适合需要服务端处理的场景。






