vue实现连接蓝牙
Vue 实现连接蓝牙的步骤
环境准备
确保项目运行在支持 Web Bluetooth API 的浏览器中(Chrome、Edge 等)。该 API 目前不支持所有浏览器,需检查兼容性。
安装依赖
在 Vue 项目中无需额外安装库,直接使用浏览器提供的 Web Bluetooth API。若需要更高级的功能,可考虑使用第三方库如 vue-bluetooth。
检查蓝牙支持
在代码中检查浏览器是否支持 Web Bluetooth API:

if (!navigator.bluetooth) {
console.error('浏览器不支持蓝牙功能');
}
请求设备连接
使用 navigator.bluetooth.requestDevice 方法请求连接设备:
async function connectToDevice() {
try {
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true, // 接受所有设备,或使用 filters 筛选特定设备
optionalServices: ['generic_access'] // 指定需要的服务
});
console.log('已连接设备:', device.name);
return device;
} catch (error) {
console.error('连接失败:', error);
}
}
连接并获取服务
连接设备后,获取 GATT 服务器并查找所需服务:

async function getService(device) {
const server = await device.gatt.connect();
const service = await server.getPrimaryService('generic_access');
return service;
}
监听特征值
获取服务后,可以监听特征值的变化:
async function listenToCharacteristic(service) {
const characteristic = await service.getCharacteristic('device_name');
characteristic.addEventListener('characteristicvaluechanged', (event) => {
console.log('特征值变化:', event.target.value);
});
await characteristic.startNotifications();
}
断开连接
在组件销毁或需要断开连接时,调用断开方法:
function disconnectDevice(device) {
if (device.gatt.connected) {
device.gatt.disconnect();
console.log('设备已断开');
}
}
在 Vue 组件中使用
将上述方法封装到 Vue 组件的 methods 中,并在模板中添加按钮触发:
<template>
<button @click="connect">连接蓝牙设备</button>
<button @click="disconnect">断开连接</button>
</template>
<script>
export default {
data() {
return {
device: null
};
},
methods: {
async connect() {
this.device = await connectToDevice();
const service = await getService(this.device);
await listenToCharacteristic(service);
},
disconnect() {
disconnectDevice(this.device);
}
}
};
</script>
注意事项
- Web Bluetooth API 仅在 HTTPS 或 localhost 环境下可用。
- 用户必须手动触发蓝牙设备请求(如点击事件),无法自动执行。
- 不同蓝牙设备的服务和特征值可能不同,需根据实际设备文档调整代码。






