useDeviceMotion
响应式 DeviceMotionEvent 为 Web 开发者提供了设备位置和方向变化速度的信息。
Demo
使用
import { useDeviceMotion } from '@vueuse/core'
const {
acceleration,
accelerationIncludingGravity,
rotationRate,
interval,
} = useDeviceMotion()
请注意:对于 iOS 系统,你需要使用
trigger并将其与用户交互绑定。获得权限后,API 将自动运行。
| 状态 | 类型 | 描述 |
|---|---|---|
acceleration | Object | 一个对象,表示设备在 X、Y 和 Z 三个轴上的加速度。 |
accelerationIncludingGravity | Object | 一个对象,表示设备在 X、Y 和 Z 三个轴上包含重力影响的加速度。 |
rotationRate | Object | 一个对象,表示设备在 alpha、beta 和 gamma 三个方向轴上的方向变化率。 |
interval | Number | 一个数字,表示从设备获取数据的时间间隔(毫秒)。 |
ensurePermissions | Boolean | 指示平台是否需要权限才能使用 API。 |
permissionGranted | Boolean | 指示用户是否已授予权限。默认始终为 false。 |
trigger | Promise<void> | 一个异步函数,用于请求用户权限。一旦获得权限,API 将自动运行。 |
你可以 在 MDN 上找到更多关于状态的信息。
组件方式使用
此函数也通过
@vueuse/components包提供一个无渲染组件版本。了解更多用法。
<template>
<UseDeviceMotion v-slot="{ acceleration }">
Acceleration: {{ acceleration }}
</UseDeviceMotion>
</template>
类型声明
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: ShallowRef<number, number>
isSupported: ComputedRef<boolean>
requirePermissions: ComputedRef<boolean>
ensurePermissions: () => Promise<void>
permissionGranted: ShallowRef<boolean, boolean>
}
export type UseDeviceMotionReturn = ReturnType<typeof useDeviceMotion>