useDeviceMotion
響應式 DeviceMotionEvent。為網頁開發者提供關於裝置位置和方向變更速度的資訊。
示範
用法
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.dev.org.tw/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>