Skip to content

useMouse

反应式鼠标位置

¥Reactive mouse position

示例

Basic Usage

x: 0
y: 0
sourceType: null

Extractor Usage

x: 0
y: 0
sourceType: null

基本用法

¥Basic Usage

ts
import { 
useMouse
} from '@vueuse/core'
const {
x
,
y
,
sourceType
} =
useMouse
()

默认情况下启用触摸。要仅检测鼠标更改,请将 touch 设置为 falsedragover 事件用于在拖动时跟踪鼠标位置。

¥Touch is enabled by default. To only detect mouse changes, set touch to false. The dragover event is used to track mouse position while dragging.

ts
const { 
x
,
y
} =
useMouse
({
touch
: false })

定制提取器

¥Custom Extractor

还可以提供自定义提取器函数来从事件中获取位置。

¥It's also possible to provide a custom extractor function to get the position from the event.

ts
import type { 
UseMouseEventExtractor
} from '@vueuse/core'
import {
useMouse
,
useParentElement
} from '@vueuse/core'
const
parentEl
=
useParentElement
()
const
extractor
:
UseMouseEventExtractor
=
event
=> (
event
instanceof
Touch
? null : [
event
.
offsetX
,
event
.
offsetY
]
) const {
x
,
y
,
sourceType
} =
useMouse
({
target
:
parentEl
,
type
:
extractor
})
js
import { useMouse, useParentElement } from '@vueuse/core'
const parentEl = useParentElement()
const extractor = (event) =>
  event instanceof Touch ? null : [event.offsetX, event.offsetY]
const { x, y, sourceType } = useMouse({ target: parentEl, type: extractor })

组件用法

¥Component Usage

vue
<template>
  <UseMouse v-slot="{ x, y }">
    x: {{ x }}
    y: {{ y }}
  </UseMouse>
</template>

类型声明

显示类型声明
typescript
export type UseMouseCoordType = "page" | "client" | "screen" | "movement"
export type UseMouseSourceType = "mouse" | "touch" | null
export type UseMouseEventExtractor = (
  event: MouseEvent | Touch,
) => [x: number, y: number] | null | undefined
export interface UseMouseOptions
  extends ConfigurableWindow,
    ConfigurableEventFilter {
  /**
   * Mouse position based by page, client, screen, or relative to previous position
   *
   * @default 'page'
   */
  type?: UseMouseCoordType | UseMouseEventExtractor
  /**
   * Listen events on `target` element
   *
   * @default 'Window'
   */
  target?: MaybeRefOrGetter<Window | EventTarget | null | undefined>
  /**
   * Listen to `touchmove` events
   *
   * @default true
   */
  touch?: boolean
  /**
   * Listen to `scroll` events on window, only effective on type `page`
   *
   * @default true
   */
  scroll?: boolean
  /**
   * Reset to initial value when `touchend` event fired
   *
   * @default false
   */
  resetOnTouchEnds?: boolean
  /**
   * Initial values
   */
  initialValue?: Position
}
/**
 * Reactive mouse position.
 *
 * @see https://vueuse.org/useMouse
 * @param options
 */
export declare function useMouse(options?: UseMouseOptions): {
  x: Ref<number, number>
  y: Ref<number, number>
  sourceType: Ref<UseMouseSourceType, UseMouseSourceType>
}
export type UseMouseReturn = ReturnType<typeof useMouse>

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号