Lzh on GitHub

响应式震动 API (Vibration API) 大多数现代移动设备都包含震动硬件,这使得软件代码可以通过使设备震动来向用户提供物理反馈。

震动 API 提供了 Web 应用访问此硬件的能力(如果存在),如果设备不支持,则不执行任何操作。

Demo

使用

震动被描述为开关脉冲的模式,其长度可以不同。

该模式可以由单个整数组成,表示震动的毫秒数;也可以由一个整数数组组成,描述震动和暂停的模式。

import { useVibrate } from '@vueuse/core'

// This vibrates the device for 300 ms
// then pauses for 100 ms before vibrating the device again for another 300 ms:
const { vibrate, stop, isSupported } = useVibrate({ pattern: [300, 100, 300] })

// Start the vibration, it will automatically stop when the pattern is complete:
vibrate()

// But if you want to stop it, you can:
stop()

类型声明

export interface UseVibrateOptions extends ConfigurableNavigator {
  /**
   *
   * Vibration Pattern
   *
   * An array of values describes alternating periods in which the
   * device is vibrating and not vibrating. Each value in the array
   * is converted to an integer, then interpreted alternately as
   * the number of milliseconds the device should vibrate and the
   * number of milliseconds it should not be vibrating
   *
   * @default []
   *
   */
  pattern?: MaybeRefOrGetter<number[] | number>
  /**
   * Interval to run a persistent vibration, in ms
   *
   * Pass `0` to disable
   *
   * @default 0
   *
   */
  interval?: number
}
/**
 * Reactive vibrate
 *
 * @see https://vueuse.org/useVibrate
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API
 * @param options
 */
export declare function useVibrate(options?: UseVibrateOptions): {
  isSupported: ComputedRef<boolean>
  pattern: MaybeRefOrGetter<number | number[]>
  intervalControls: Pausable | undefined
  vibrate: (pattern?: number | number[]) => void
  stop: () => void
}
export type UseVibrateReturn = ReturnType<typeof useVibrate>