当前位置:首页 > VUE

vue实现蓝牙开关功能

2026-02-23 16:30:05VUE

Vue 实现蓝牙开关功能

准备工作

确保项目环境支持 Web Bluetooth API,该 API 需要在 HTTPS 环境或本地开发环境(如 localhost)中运行。检查浏览器兼容性,Chrome、Edge 和 Opera 支持较好。

检测蓝牙支持

在 Vue 组件中,通过 navigator.bluetooth 检测浏览器是否支持蓝牙功能。若不支持,需提示用户更换浏览器或环境。

vue实现蓝牙开关功能

mounted() {
  if (!navigator.bluetooth) {
    console.error('Web Bluetooth API is not supported in this browser.');
  }
}

请求蓝牙设备

使用 navigator.bluetooth.requestDevice 方法扫描并连接蓝牙设备。需指定设备过滤条件(如服务 UUID)。

methods: {
  async connectToDevice() {
    try {
      const device = await navigator.bluetooth.requestDevice({
        acceptAllDevices: true, // 或指定 filters
        optionalServices: ['generic_access'] // 需要的服务
      });
      this.device = device;
      console.log('Connected to:', device.name);
    } catch (error) {
      console.error('Connection failed:', error);
    }
  }
}

开关功能实现

通过获取设备的 GATT 服务并操作特征值(Characteristic)实现开关控制。假设蓝牙设备有一个可写的特征值用于控制开关。

vue实现蓝牙开关功能

methods: {
  async toggleBluetoothDevice(powerOn) {
    if (!this.device) {
      console.error('No device connected.');
      return;
    }
    try {
      const server = await this.device.gatt.connect();
      const service = await server.getPrimaryService('generic_access');
      const characteristic = await service.getCharacteristic('power_control');
      const value = powerOn ? new Uint8Array([1]) : new Uint8Array([0]);
      await characteristic.writeValue(value);
      console.log('Device state set to:', powerOn ? 'ON' : 'OFF');
    } catch (error) {
      console.error('Toggle failed:', error);
    }
  }
}

断开连接

主动断开蓝牙连接以释放资源。

methods: {
  disconnectDevice() {
    if (this.device && this.device.gatt.connected) {
      this.device.gatt.disconnect();
      console.log('Device disconnected.');
    }
  }
}

完整示例组件

整合上述代码的 Vue 组件示例:

<template>
  <div>
    <button @click="connectToDevice">Connect</button>
    <button @click="toggleBluetoothDevice(true)">Turn On</button>
    <button @click="toggleBluetoothDevice(false)">Turn Off</button>
    <button @click="disconnectDevice">Disconnect</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      device: null
    };
  },
  methods: {
    async connectToDevice() {
      try {
        const device = await navigator.bluetooth.requestDevice({
          acceptAllDevices: true,
          optionalServices: ['generic_access']
        });
        this.device = device;
      } catch (error) {
        console.error(error);
      }
    },
    async toggleBluetoothDevice(powerOn) {
      if (!this.device) return;
      try {
        const server = await this.device.gatt.connect();
        const service = await server.getPrimaryService('generic_access');
        const characteristic = await service.getCharacteristic('power_control');
        await characteristic.writeValue(new Uint8Array([powerOn ? 1 : 0]));
      } catch (error) {
        console.error(error);
      }
    },
    disconnectDevice() {
      if (this.device?.gatt.connected) {
        this.device.gatt.disconnect();
      }
    }
  }
};
</script>

注意事项

  • 权限:首次调用 requestDevice 会触发用户授权弹窗,需用户手动允许。
  • 错误处理:蓝牙操作可能因信号、权限或设备问题失败,需捕获并处理异常。
  • 设备兼容性:不同蓝牙设备的服务 UUID 和特征值可能不同,需根据实际设备文档调整代码。

通过以上步骤,可以在 Vue 项目中实现基础的蓝牙开关控制功能。

标签: 蓝牙功能
分享给朋友:

相关文章

vue实现注册功能

vue实现注册功能

实现注册功能的基本步骤 在Vue中实现注册功能通常需要结合前端表单和后端API交互。以下是常见的实现方式: 创建注册表单组件 <template> <div class="re…

vue实现倒计时功能

vue实现倒计时功能

vue实现倒计时功能 在Vue中实现倒计时功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用setInterval和clearInterval 创建一个倒计时组件,利用setInter…

vue实现按钮实现点击功能

vue实现按钮实现点击功能

实现按钮点击功能 在Vue中实现按钮点击功能可以通过v-on指令或@缩写来绑定事件。以下是几种常见的实现方式: 使用v-on指令 通过v-on:click绑定点击事件,触发定义在methods中的方…

vue实现功能列表

vue实现功能列表

Vue 实现功能列表的方法 在 Vue 中实现功能列表通常涉及数据绑定、列表渲染、事件处理和状态管理。以下是几种常见的方法: 数据驱动列表渲染 使用 v-for 指令可以轻松实现列表渲染。假设有一个…

vue实现筛选功能

vue实现筛选功能

实现筛选功能的基本思路 在Vue中实现筛选功能通常涉及数据绑定、计算属性和方法的使用。通过监听用户输入或选择,动态过滤数据列表。 基础筛选实现 创建一个输入框绑定到Vue实例的data属性,使用计算…

php实现回复功能

php实现回复功能

实现回复功能的基本步骤 在PHP中实现回复功能通常涉及数据库操作、表单处理和前后端交互。以下是实现回复功能的关键步骤: 数据库设计 创建包含回复数据的表结构,例如: CREATE TABLE re…