当前位置:首页 > VUE

vue实现长按事

2026-01-18 02:39:28VUE

Vue 实现长按事件的方法

使用原生事件监听

通过 @mousedown@mouseup 结合 setTimeout 实现长按逻辑。在 mousedown 时启动计时器,mouseup 时清除计时器。

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

<script>
export default {
  methods: {
    startPress() {
      this.timer = setTimeout(() => {
        console.log('长按事件触发');
      }, 1000); // 1秒后触发长按
    },
    endPress() {
      clearTimeout(this.timer);
    }
  }
};
</script>

使用自定义指令

封装一个 v-longpress 指令,便于复用。指令内部逻辑与原生事件类似,但通过指令绑定更简洁。

<template>
  <button v-longpress="handleLongPress">长按指令</button>
</template>

<script>
export default {
  directives: {
    longpress: {
      bind(el, binding) {
        let timer;
        el.addEventListener('mousedown', () => {
          timer = setTimeout(() => {
            binding.value();
          }, 1000);
        });
        el.addEventListener('mouseup', () => {
          clearTimeout(timer);
        });
      }
    }
  },
  methods: {
    handleLongPress() {
      console.log('自定义指令长按触发');
    }
  }
};
</script>

移动端适配

对于触摸事件,需替换为 touchstarttouchend。同时注意防止触摸时的默认行为(如页面滚动)。

<template>
  <div @touchstart="startTouch" @touchend="endTouch">长按触摸</div>
</template>

<script>
export default {
  methods: {
    startTouch(e) {
      e.preventDefault(); // 阻止默认行为
      this.timer = setTimeout(() => {
        console.log('触摸长按触发');
      }, 1000);
    },
    endTouch() {
      clearTimeout(this.timer);
    }
  }
};
</script>

第三方库

使用如 vue-touchhammer.js 等库简化实现。以 vue-touch 为例:

import VueTouch from 'vue-touch';
Vue.use(VueTouch, { name: 'v-touch' });

<template>
  <v-touch @press="onPress">库实现长按</v-touch>
</template>

<script>
export default {
  methods: {
    onPress() {
      console.log('vue-touch 长按事件');
    }
  }
};
</script>

注意事项

  • 清除计时器:确保在组件销毁时清除所有计时器,避免内存泄漏。
  • 性能优化:长按时间较长时,避免频繁触发回调。
  • 事件冒泡:根据需求决定是否阻止事件冒泡(如 e.stopPropagation())。

vue实现长按事

标签: vue长按事
分享给朋友:

相关文章

vue实现3d宇宙

vue实现3d宇宙

Vue实现3D宇宙效果 使用Three.js库 Three.js是一个强大的JavaScript 3D库,可以轻松集成到Vue项目中。安装Three.js依赖: npm install three…

eventbus vue实现

eventbus vue实现

EventBus 实现原理 EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。 创建 EventBus 在 Vue 项目中创建一个独…

vue实现递归

vue实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身:…

vue 实现blog

vue 实现blog

Vue 实现博客的基本步骤 使用 Vue 实现博客可以分为前端和后端两部分,前端使用 Vue.js 框架,后端可以选择 Node.js、Python 或其他服务端语言。以下是一个基于 Vue 的博客实…

vue computed 实现

vue computed 实现

computed 的基本用法 在 Vue 中,computed 用于声明计算属性,这些属性基于响应式依赖进行缓存。只有当依赖发生变化时,计算属性才会重新计算。 new Vue({ data: {…

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基…