useDeviceMotion
响应式 DeviceMotionEvent。 为 Web 开发者提供有关设备位置和方向变化速度的信息。
演示
用法
js
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
包提供了一个无渲染组件版本。 了解更多关于用法的信息。
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.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>