useMouse
鼠标位置的响应式状态
Demo
基本用法
ts
import { useMouse } from '@vueuse/core'
const { x, y, sourceType } = useMouse()
默认情况下启用了触摸功能。要仅检测鼠标变化,请将 touch
设置为 false
。 dragover
事件用于跟踪拖动时的鼠标位置。
ts
const { x, y } = useMouse({ touch: false })
自定义提取器
还可以提供自定义提取器函数来从事件中获取位置信息。
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 })
组件使用
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 {
/**
* 基于页面、客户端、屏幕或相对于上一个位置的鼠标位置
*
* @default 'page'
*/
type?: UseMouseCoordType | UseMouseEventExtractor
/**
* 在`target`元素上监听事件
*
* @default 'Window'
*/
target?: MaybeRefOrGetter<Window | EventTarget | null | undefined>
/**
* 监听 `touchmove` 事件
*
* @default true
*/
touch?: boolean
/**
* 在窗口上监听 `scroll` 事件,仅在 `type` 为 `page` 时有效
*
* @default true
*/
scroll?: boolean
/**
* 当触发 `touchend` 事件时重置为初始值
*
* @default false
*/
resetOnTouchEnds?: boolean
/**
* 初始值
*/
initialValue?: 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>
Source
贡献者
Anthony Fu
丶远方
Jelf
Anthony Fu
Eduardo Luiz Schilling
karukenert
Cats Juice
RAX7
François Lévesque
vaakian X
Sergey Danilchenko
lzdFeiFei
Scott Bedard
Marshall Thompson
Shinigami
wheat
Alex Kozack
Antério Vieira
变更日志
v10.4.0
on 8/25/2023v10.1.0
on 4/22/2023v10.0.0-beta.4
on 4/13/2023v9.11.0
on 1/17/2023v9.10.0
on 1/3/2023