Skip to content

v-pan

平移/拖拽手势检测。

起始版本: 1.5.0

用法

基本

vue
<template>
  <div v-pan="handlePan">滑动我</div>
</template>

<script setup>
function handlePan(e) {
  console.log('方向:', e.direction)
  console.log('距离:', e.distance)
}
</script>

限制方向

vue
<template>
  <div v-pan="{
    onPan: handlePan,
    direction: 'horizontal',
    threshold: 20
  }">
    仅水平滑动
  </div>
</template>

API

PanEvent

属性类型描述
originalEventTouchEvent | MouseEvent原始事件
direction'left' | 'right' | 'up' | 'down'滑动方向
deltaXnumberX 轴偏移量
deltaYnumberY 轴偏移量
distancenumber滑动距离
xnumber当前 X 坐标
ynumber当前 Y 坐标
startXnumber起始 X 坐标
startYnumber起始 Y 坐标
isPanningboolean是否正在滑动
isFirstboolean是否刚开始
isFinalboolean是否已结束
velocitynumber滑动速度

选项

选项类型默认值描述
onStart(e: PanEvent) => void-滑动开始回调
onPan(e: PanEvent) => void-滑动中回调
onEnd(e: PanEvent) => void-滑动结束回调
thresholdnumber10触发滑动的最小距离
direction'horizontal' | 'vertical' | 'all''all'方向限制
preventDefaultbooleantrue是否阻止默认行为
stopPropagationbooleanfalse是否阻止事件冒泡
pointers('touch' | 'mouse')[]['touch', 'mouse']监听的指针类型

绑定值类型

ts
type PanBinding = PanOptions['onPan'] | PanOptions

Composable 用法

你也可以使用 usePan composable 来实现相同功能:

vue
<script setup>
import { ref, onMounted } from 'vue'
import { usePan } from 'directix'

const containerRef = ref(null)
const { isPanning, direction, distance, bind } = usePan({
  onPan: (e) => console.log('滑动:', e.direction, e.distance),
  direction: 'horizontal'
})

onMounted(() => bind(containerRef.value))
</script>

<template>
  <div ref="containerRef">滑动我</div>
  <p v-if="isPanning">正在滑动: {{ direction }}, 距离: {{ distance }}</p>
</template>

API

typescript
interface PanEvent {
  direction: 'left' | 'right' | 'up' | 'down'
  deltaX: number
  deltaY: number
  distance: number
  x: number
  y: number
  startX: number
  startY: number
  isPanning: boolean
  isFirst: boolean
  isFinal: boolean
  velocity: number
}

interface UsePanOptions {
  /** 滑动开始回调 */
  onStart?: (e: PanEvent) => void
  /** 滑动中回调 */
  onPan?: (e: PanEvent) => void
  /** 滑动结束回调 */
  onEnd?: (e: PanEvent) => void
  /** 触发滑动的最小距离 */
  threshold?: number
  /** 方向限制 */
  direction?: 'horizontal' | 'vertical' | 'all'
  /** 是否阻止默认行为 */
  preventDefault?: boolean
  /** 监听的指针类型 */
  pointers?: ('touch' | 'mouse')[]
}

interface UsePanReturn {
  /** 是否正在滑动 */
  isPanning: Ref<boolean>
  /** 当前滑动方向 */
  direction: Ref<'left' | 'right' | 'up' | 'down' | null>
  /** 滑动距离 */
  distance: Ref<number>
  /** 绑定到元素 */
  bind: (element: HTMLElement) => () => void
}

基于 MIT 许可发布