Skip to content

useDeviceMotion

反应式 DeviceMotionEvent。为 Web 开发者提供有关设备位置和方向变化速度的信息。

¥Reactive DeviceMotionEvent. Provide web developers with information about the speed of changes for the device's position and orientation.

示例

Device Motion:
Not supported by your current browser.

用法

¥Usage

js
import { useDeviceMotion } from '@vueuse/core'

const {
  acceleration,
  accelerationIncludingGravity,
  rotationRate,
  interval,
} = useDeviceMotion()

注意:对于 iOS,需要使用 trigger 并将其与用户交互绑定。授予权限后,API 将自动运行

¥Note: For iOS, you need to use trigger and bind it with user interaction. After permission granted, the API will run automatically

状态类型描述
accelerationobject给出设备在 X、Y 和 Z 三个轴上的加速度的对象。
accelerationIncludingGravityobject在重力作用下给出设备在 X、Y 和 Z 三个轴上的加速度的对象。
rotationRateobject给出设备在三个方向轴 alpha、beta 和 gamma 上的方向变化率的对象。
intervalNumber表示从设备获取数据的时间间隔(以毫秒为单位)的数字。
ensurePermissionsboolean表示平台是否需要使用 API 的权限
permissionGrantedboolean表示用户是否已授予权限。默认值始终为 false
triggerPromise<void>用于请求用户权限的异步函数。一旦授予权限,API 就会自动运行

你可以找到 有关 MDN 上的状态的更多信息

¥You can find more information about the state on the MDN.

组件用法

¥Component Usage

vue
<template>
  <UseDeviceMotion v-slot="{ acceleration }">
    Acceleration: {{ acceleration }}
  </UseDeviceMotion>
</template>

类型声明

显示类型声明
typescript
export interface DeviceMotionOptions
  extends ConfigurableWindow,
    ConfigurableEventFilter {
  /**
   * Request for permissions immediately if it's not granted,
   * otherwise label and deviceIds could be empty
   *
   * @default false
   */
  requestPermissions?: boolean
}
/**
 * Reactive DeviceMotionEvent.
 *
 * @see https://vueuse.org/useDeviceMotion
 * @param options
 */
export declare function useDeviceMotion(options?: DeviceMotionOptions): {
  acceleration: Ref<
    DeviceMotionEventAcceleration | null,
    DeviceMotionEventAcceleration | null
  >
  accelerationIncludingGravity: Ref<
    DeviceMotionEventAcceleration | null,
    DeviceMotionEventAcceleration | null
  >
  rotationRate: Ref<
    DeviceMotionEventRotationRate | null,
    DeviceMotionEventRotationRate | null
  >
  interval: Ref<number, number>
  isSupported: ComputedRef<boolean>
  requirePermissions: ComputedRef<boolean>
  ensurePermissions: () => Promise<void>
  permissionGranted: Ref<boolean, boolean>
}
export type UseDeviceMotionReturn = ReturnType<typeof useDeviceMotion>

源代码

源代码示例文档

变更日志

v12.4.0 on 1/10/2025
dd316 - feat: use passive event handlers everywhere is possible (#4477)
v12.1.0 on 12/22/2024
cf729 - feat: add permission controls, improve destructure (#4127)

VueUse 中文网 - 粤ICP备13048890号