当前位置:首页 > VUE

vue实现长按事件

2026-01-08 15:29:37VUE

实现长按事件的几种方法

在Vue中实现长按事件可以通过多种方式完成,以下是几种常见的实现方法:

使用原生事件监听

通过@mousedown@mouseup@touchstart@touchend组合实现长按效果:

<template>
  <button 
    @mousedown="startPress"
    @mouseup="endPress"
    @touchstart="startPress"
    @touchend="endPress"
  >长按我</button>
</template>

<script>
export default {
  data() {
    return {
      pressTimer: null
    }
  },
  methods: {
    startPress(e) {
      this.pressTimer = setTimeout(() => {
        this.handleLongPress(e)
      }, 1000) // 1秒触发长按
    },
    endPress() {
      clearTimeout(this.pressTimer)
    },
    handleLongPress(e) {
      console.log('长按事件触发', e)
    }
  }
}
</script>

使用自定义指令

创建可重用的长按指令:

vue实现长按事件

// longpress.js
const longpress = {
  bind: function(el, binding, vNode) {
    if (typeof binding.value !== 'function') {
      throw 'callback must be a function'
    }

    let pressTimer = null
    const start = (e) => {
      if (e.type === 'click' && e.button !== 0) return

      if (pressTimer === null) {
        pressTimer = setTimeout(() => {
          binding.value(e)
        }, 1000)
      }
    }
    const cancel = () => {
      if (pressTimer !== null) {
        clearTimeout(pressTimer)
        pressTimer = null
      }
    }

    el.addEventListener('mousedown', start)
    el.addEventListener('touchstart', start)
    el.addEventListener('click', cancel)
    el.addEventListener('mouseout', cancel)
    el.addEventListener('touchend', cancel)
    el.addEventListener('touchcancel', cancel)
  }
}

export default longpress

在Vue中使用:

// main.js
import longpress from './directives/longpress'

Vue.directive('longpress', longpress)
<template>
  <button v-longpress="handleLongPress">长按我</button>
</template>

<script>
export default {
  methods: {
    handleLongPress() {
      console.log('长按事件触发')
    }
  }
}
</script>

使用第三方库

可以使用现成的Vue长按库,如vue-long-click

vue实现长按事件

安装:

npm install vue-long-click

使用:

import VueLongClick from 'vue-long-click'

Vue.use(VueLongClick, {
  delay: 1000,
  interval: 50
})
<template>
  <button v-longclick="handleLongPress">长按我</button>
</template>

注意事项

  • 移动端和桌面端的事件处理需要分别考虑touchmouse事件
  • 防止长按触发后同时触发点击事件
  • 考虑性能优化,及时清除定时器
  • 可以根据需求调整长按的时间阈值

以上方法可以根据项目需求选择最适合的实现方式,自定义指令提供了更好的复用性,而第三方库则更加简单易用。

标签: 事件vue
分享给朋友:

相关文章

vue实现多选联动

vue实现多选联动

vue实现多选联动的方法 使用v-model绑定数组 在Vue中,可以通过v-model绑定一个数组来实现多选联动。当复选框被选中或取消选中时,数组会自动更新。 <template>…

vue实现下拉层级

vue实现下拉层级

Vue实现下拉层级菜单 使用Vue实现下拉层级菜单可以通过递归组件或动态渲染的方式完成。以下是两种常见实现方法: 递归组件实现 创建一个递归组件处理多级菜单结构: <template>…

vue穿梭框组件实现

vue穿梭框组件实现

实现基础穿梭框组件 在Vue中实现穿梭框组件,可以使用<el-transfer>(Element UI)或手动实现。以下是手动实现的核心逻辑: <template> &l…

vue实现拖放

vue实现拖放

Vue 实现拖放功能 Vue 中实现拖放功能通常可以通过 HTML5 的原生拖放 API 或第三方库(如 vuedraggable)来实现。以下是两种方法的详细说明。 使用 HTML5 原生拖放 A…

vue实现异步

vue实现异步

Vue 实现异步操作的常见方法 Vue 提供了多种方式来处理异步操作,包括数据获取、事件处理等场景。 使用 async/await 在 Vue 方法中可以直接使用 async/await 语法处理异…

vue实现前端

vue实现前端

Vue 实现前端的核心方法与步骤 安装 Vue 项目 使用 Vue CLI 或 Vite 创建项目。Vue CLI 是传统构建工具,Vite 是新一代轻量级工具。 npm init vue@la…