VueUse 学习 —— useBluetooth

509 阅读2分钟

useBluetooth 是 vueuse 提供的响应式 Web Bluetooth API。用于处理与蓝牙设备相关的任务,如连接蓝牙设备、读取设备特征值等, 它可以帮助简化蓝牙相关功能的开发。

该函数的使用方式如下:

import { useBluetooth } from '@vueuse/core'

const {
  isSupported,
  isConnected,
  device,
  requestDevice,
  server,
} = useBluetooth({
  acceptAllDevices: true,
})
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>

源码分析

源码地址

  • 定义两个 ts 接口 UseBluetoothRequestDeviceOptionsUseBluetoothOptions,它们分别表示了请求蓝牙设备的选项和整个 useBluetooth Hook 的选项。这些选项包括了一些用于配置请求的属性,如过滤器、可选服务等。
  • 定义了一个名为 useBluetooth 的函数。这个函数接受一个选项对象,包含了用于配置请求和处理蓝牙设备的逻辑。函数中主要的逻辑包括:
    • 使用 useSupported Hook 来检测当前环境是否支持蓝牙功能。
    • 使用 shallowRef 来创建了一个存储蓝牙设备的引用变量 device
    • 使用 watch 监听 device 的变化,一旦设备发生变化,就会调用connectToBluetoothGATTServer 函数。
    • 定义了 requestDevice 函数,用于请求蓝牙设备。根据配置参数和过滤器,尝试请求蓝牙设备,并在成功或失败时设置 deviceerror 变量。
    • 使用 computed 创建了一个 isConnected 计算属性,用于判断蓝牙设备是否已连接。
    • 定义了 connectToBluetoothGATTServer 函数,用于连接蓝牙 GATT 服务器。这个函数尝试连接设备的 GATT 服务器,如果成功则设置 server 变量,否则设置 error
    • 使用 tryOnMountedtryOnScopeDispose 来在组件挂载和销毁时分别连接和断开蓝牙设备的 GATT 服务器。

useBluetooth 函数返回一个对象,其中包含了一些属性和方法,如 isSupportedisConnecteddevicerequestDeviceservererror

相关知识 navigator?.bluetooth.requestDevice