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端