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