跳到內容

useDeviceMotion

分類
導出大小
758 B
最後變更
3 週前

響應式 DeviceMotionEvent。為網頁開發者提供關於裝置位置和方向變更速度的資訊。

示範

裝置 Motion
您目前的瀏覽器不支援。

用法

js
import { useDeviceMotion } from '@vueuse/core'

const {
  acceleration,
  accelerationIncludingGravity,
  rotationRate,
  interval,
} = useDeviceMotion()

注意:對於 iOS,您需要使用 trigger 並將其與用戶互動綁定。授權後,API 將自動運行

狀態類型描述
accelerationobject一個物件,提供裝置在 X、Y 和 Z 三軸上的加速度。
accelerationIncludingGravityobject一個物件,提供裝置在 X、Y 和 Z 三軸上包含重力影響的加速度。
rotationRateobject一個物件,提供裝置在 alpha、beta 和 gamma 三個方向軸上的方向變化率。
intervalNumber一個數字,表示從裝置取得資料的時間間隔,以毫秒為單位。
ensurePermissionsboolean指示平台是否需要權限才能使用 API
permissionGrantedboolean指示使用者是否已授與權限。預設值始終為 false
triggerPromise<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>

原始碼

SourceDemoDocs

貢獻者

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

更新日誌

v12.4.0 on 1/10/2025
dd316 - feat: use passive event handlers everywhere is possible (#4477)
v12.1.0 on 12/22/2024
cf729 - feat: add permission controls, improve destructure (#4127)
v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)

Released under the MIT License.