Lzh on GitHub

响应式鼠标按下状态。通过在目标元素上的 mousedowntouchstart 事件触发,并通过在窗口上的 mouseupmouseleavetouchendtouchcancel 事件释放。

基本用法

import { useMousePressed } from '@vueuse/core'

const { pressed } = useMousePressed()

默认启用触控。若要 仅检测鼠标变化,请将 touch 设置为 false

const { pressed } = useMousePressed({ touch: false })

若要仅捕获 特定元素上的 mousedowntouchstart 事件,你可以通过传递元素的引用来指定 target

<script setup lang="ts">
import { useTemplateRef } from 'vue'

const el = useTemplateRef<HTMLDivElement>('el')
const { pressed } = useMousePressed({ target: el })
</script>

<template>
  <div ref="el">
    Only clicking on this element will trigger the update.
  </div>
</template>

组件用法

此函数还通过 @vueuse/components 提供了 无渲染组件版本了解更多关于用法的信息

<template>
  <UseMousePressed v-slot="{ pressed }">
    Is Pressed: {{ pressed }}
  </UseMousePressed>
</template>

类型声明

export interface MousePressedOptions extends ConfigurableWindow {
  /**
   * Listen to `touchstart` `touchend` events
   *
   * @default true
   */
  touch?: boolean
  /**
   * Listen to `dragstart` `drop` and `dragend` events
   *
   * @default true
   */
  drag?: boolean
  /**
   * Add event listerners with the `capture` option set to `true`
   * (see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#capture))
   *
   * @default false
   */
  capture?: boolean
  /**
   * Initial values
   *
   * @default false
   */
  initialValue?: boolean
  /**
   * Element target to be capture the click
   */
  target?: MaybeComputedElementRef
  /**
   * Callback to be called when the mouse is pressed
   *
   * @param event
   */
  onPressed?: (event: MouseEvent | TouchEvent | DragEvent) => void
  /**
   * Callback to be called when the mouse is released
   *
   * @param event
   */
  onReleased?: (event: MouseEvent | TouchEvent | DragEvent) => void
}
/**
 * Reactive mouse pressing state.
 *
 * @see https://vueuse.org/useMousePressed
 * @param options
 */
export declare function useMousePressed(options?: MousePressedOptions): {
  pressed: ShallowRef<boolean, boolean>
  sourceType: ShallowRef<UseMouseSourceType, UseMouseSourceType>
}
export type UseMousePressedReturn = ReturnType<typeof useMousePressed>