当前位置:首页 > 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电影功能实现 数据获取与展示 使用Axios或Fetch API从电影API获取数据,例如TMDB或豆瓣API。在Vue组件的created或mounted生命周期钩子中发起请求,将返回的电影数…

vue实现产品使用功能

vue实现产品使用功能

Vue 实现产品功能的关键方法 组件化开发 使用Vue的单文件组件(.vue)将产品功能模块化,每个功能拆分为独立组件。例如产品列表、详情页、购物车等可分别封装为ProductList.vue、Pro…

uniapp实现选项卡功能

uniapp实现选项卡功能

实现选项卡功能的基本方法 在uniapp中实现选项卡功能通常需要使用uni-segmented-control组件或自定义样式结合swiper组件。以下是两种常见实现方式: 使用uni-se…

vue电影功能实现

vue电影功能实现

Vue 电影功能实现 数据获取与展示 使用 Axios 或 Fetch API 从电影 API(如 TMDb、豆瓣 API)获取数据。在 Vue 的 created 或 mounted 生命周期钩子中…

vue实现功能列表

vue实现功能列表

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

h5实现手机摇一摇功能

h5实现手机摇一摇功能

实现原理 手机摇一摇功能基于设备加速度传感器(DeviceMotionEvent),通过监听设备的加速度变化来判断用户是否进行了摇晃动作。HTML5提供了相关API获取设备传感器数据。 基本…