Vue中可以通过v-longpress指令来实现长按事件。

首先,在Vue实例中注册指令:

Vue.directive('longpress', {
  bind: function (el, binding, vNode) {
    // 长按时间阈值,单位为毫秒
    let pressTime = 500
    // 记录定时器ID
    let timerId = null
    // 绑定 touchstart 事件
    el.addEventListener('touchstart', function (event) {
      // 防止重复绑定
      if (timerId) {
        clearTimeout(timerId)
      }
      // 开始计时
      timerId = setTimeout(() => {
        // 调用回调函数
        binding.value(event)
      }, pressTime)
    }, false)
    // 绑定 touchend 事件
    el.addEventListener('touchend', function (event) {
      // 清除定时器
      clearTimeout(timerId)
    }, false)
  }
})

然后,在模板中使用指令:

<template>
  <div v-longpress="longPressHandler">长按我</div>
</template>

其中,longPressHandler是长按事件的回调函数,可以在这个函数中编写长按后的操作。

vue 长按事件

原文地址: http://www.cveoy.top/t/topic/bk5C 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录