跳到主要内容

useDeviceMotion

分类
导出大小
1.19 kB
上次更改
8 个月前

响应式的 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
triggerPromise<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
>

来源

源码演示文档

贡献者

Anthony Fu
Antério Vieira
IlyaL
SerKo
Guspan Tanadi
Fernando Fernández
thefeymesaleng
Anthony Fu
vaakian X
Shinigami
wheat
Alex Kozack

更新日志

8c521 - feat(components)!: 重构组件并使其保持一致 (#4912)
v12.4.0
dd316 - feat: 尽可能在所有地方使用被动事件处理程序 (#4477)
v12.1.0
cf729 - feat: 添加权限控制,改进解构 (#4127)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。