移动端H5长按事件 vue自定义指令

 1 import Vue from 'vue'
 2 Vue.directive('longpress', function (el, binding){
 3   var timer = null;
 4   var start = function (e) {
 5       // 如果是点击事件,不启动计时器,直接返回
 6       if (e.type === 'click'){
 7           return
 8       }
 9       if (timer == null){
10           // 创建定时器 ( 2s之后执行长按功能函数 )
11           timer = setTimeout(function () {
12               //执行长按功能函数
13               binding.value()
14           },2000)
15       }
16   }
17   var cancel = function () {
18       if (timer !== null){
19           clearTimeout(timer)
20           timer = null
21       }
22   }
23 
24   // 添加事件监听器
25   el.addEventListener("mousedown", start);
26   el.addEventListener("touchstart", start);
27 
28   // 取消计时器
29   el.addEventListener("click", cancel);
30   el.addEventListener("mouseout", cancel);
31   el.addEventListener("touchend", cancel);
32   el.addEventListener("touchcancel", cancel);
33 })

1.在src目录下 新建文件夹utils文件夹,然后新建derective.js,复制上方代码,粘贴到derective.js;
2.在main.js中引入 该自定义指令js
3.在html中可以这样使用即可 

<h2 v-longpress="handleLongClick">测试长按事件是否生效</h2>

总结:支持移动端跟pc端


posted @ 2019-12-18 17:16  ____chen  阅读(2736)  评论(0编辑  收藏  举报