外观
useTouch - 触摸手势
约 483 字大约 2 分钟
2026-11-29
介绍
useTouch 统一封装触摸开始与移动事件,输出起始坐标、相对起点的位移和滑动方向,可直接用于轮播、滑块、下拉刷新等手势场景。
坐标读取兼容各端:优先取 touches[0],touchcancel 时回退 changedTouches[0],H5 鼠标/指针事件直接取事件自身的坐标;clientX / clientY 缺失时回退 pageX / pageY。
基本用法
import { useTouch } from '@/uni_modules/uview-unix'
const touch = useTouch()
const onTouchStart = (event: any) => {
touch.start(event)
}
const onTouchMove = (event: any) => {
touch.move(event)
console.log(touch.deltaX.value, touch.direction.value)
}
const onTouchEnd = () => {
if (touch.isTap()) {
console.log('点击')
} else if (touch.isHorizontal() && touch.deltaX.value > 50) {
console.log('向右滑动')
}
touch.reset()
}模板绑定示例:<view @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
API
useTouch(): UnUseTouch
参数
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| - | 无入参 | - | - |
start 与 move 接收平台传入的触摸事件对象,isTap 可传入自定义阈值。
返回值
| 方法/属性 | 说明 | 类型 |
|---|---|---|
| startX | 触摸起点 X 坐标 | Ref<number> |
| startY | 触摸起点 Y 坐标 | Ref<number> |
| deltaX | 相对起点的水平位移 | Ref<number> |
| deltaY | 相对起点的垂直位移 | Ref<number> |
| direction | 滑动方向:horizontal、vertical,尚未判断时为空字符串 | Ref<'' | 'horizontal' | 'vertical'> |
| start | 记录起点坐标,并重置位移与方向 | (event: any) => void |
| move | 更新位移,并按位移绝对值大小写入 direction | (event: any) => void |
| reset | 位移与方向重置为 0 和空字符串(不清除起点坐标) | () => void |
| getDelta | 获取当前位移 | () => UnTouchPoint |
| isVertical | 是否为垂直滑动,判断条件为 Math.abs(deltaX) < Math.abs(deltaY) | () => boolean |
| isHorizontal | 是否为水平滑动,判断条件为 Math.abs(deltaX) >= Math.abs(deltaY) | () => boolean |
| isTap | 位移是否小于阈值,可作点击判定 | (threshold?: number) => boolean |
UnTouchPoint 为 { x: number, y: number }。
示例
手势判定
import { useTouch } from '@/uni_modules/uview-unix'
const touch = useTouch()
const onTouchStart = (event: any) => touch.start(event)
const onTouchMove = (event: any) => touch.move(event)
const onTouchEnd = () => {
// 自定义点击阈值,默认 5px
if (touch.isTap(10)) {
console.log('点击')
}
if (touch.isVertical()) {
console.log('垂直滑动', touch.getDelta().y)
} else {
console.log('水平滑动', touch.getDelta().x)
}
touch.reset()
}