VueUse onLongPress 长按事件

VueUse onLongPress 长按事件,比如长按1秒按钮之后才触发一个事件,像你经常在app看到的长按删除功能就是通过该功能实现的。

代码示例

<script setup lang="ts">
import { ref } from 'vue'
import { onLongPress } from '@vueuse/core'
// vueuse 中文文档:https://www.itxst.com/vueuse/tutorial.html
// 定义一个变量关联长按元素
const btnEL = ref<HTMLElement | null>(null)
// 是否长按
const isLongPressed = ref(false)

// 长按事件
function onLongPressCallback(e: PointerEvent) {
  isLongPressed.value = true
}

// 恢复状态
function resetHook() {
 isLongPressed.value = false
}

// 绑定按钮元素和回调事件
onLongPress(
  btnEL,
  onLongPressCallback,
  {
    //按1秒才触发事件
    delay:1000,
    //长按时就算手指移动30像素 也算长按
    distanceThreshold:30,
    modifiers: {
      // true 表示只触发一次
      once:false,
      // true 表示阻止事件往下传递
      stop: false,
      // true 表示只能长按btnEL元素才能触发,如果是它的遮罩层父元素长按也不行
      self: true,
      prevent:true,
      capture:true
    }
  }
)
</script>
<template>
  <p>Long Pressed: {{ isLongPressed }}</p>
  <button ref="btnEL"  >
    长按1秒
  </button>
  <button @click="resetHook">
   恢复
  </button>
</template>

组件示例

<script setup lang="ts">
import { ref } from 'vue'
import { OnLongPress } from '@vueuse/components'

const isLongPressed = ref(false)

function onLongPressCallback(e: PointerEvent) {
  isLongPressed.value = true
}
function reset() {
 isLongPressed .value = false
}
</script>
<template>
  <p>Long Pressed: {{ isLongPressed  }}</p>
  <OnLongPress
    as="button" 
    @trigger="onLongPressCallback"
  >
    长按
  </OnLongPress>
  <button @click="reset">
    恢复
  </button>
</template>

指令示例

<script setup lang="ts">
import { ref } from 'vue'
import { vOnLongPress } from '@vueuse/components'

const isLongPressed = ref(false)

function onLongPressCallback(e: PointerEvent) {
 isLongPressed.value = true
}
function resetDirective() {
  isLongPressed.value = false
}
</script>
<template>
  <p>Long Pressed: {{ isLongPressed }}</p>
  <button v-on-long-press.prevent="onLongPressCallback">
    长按
  </button>
  <button v-on-long-press="[onLongPressCallback, { delay: 1000, modifiers: { stop: true } }]">
     长按 (1秒并禁止事件穿透)
  </button>
  <button  @click="resetDirective">
    Reset
  </button>
</template>

在线例子

例子

类型定义

export interface OnLongPressOptions {
  /**
   * Time in ms till `longpress` gets called
   *
   * @default 500
   */
  delay?: number
  modifiers?: OnLongPressModifiers
  /**
   * Allowance of moving distance in pixels,
   * The action will get canceled When moving too far from the pointerdown position.
   * @default 10
   */
  distanceThreshold?: number | false
}
export interface OnLongPressModifiers {
  stop?: boolean
  once?: boolean
  prevent?: boolean
  capture?: boolean
  self?: boolean
}
export declare function onLongPress(
  target: MaybeElementRef,
  handler: (evt: PointerEvent) => void,
  options?: OnLongPressOptions,
): () => void