longpress.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * v-longpress
  3. * 长按指令,长按时触发事件
  4. */
  5. import type { Directive, DirectiveBinding } from "vue";
  6. const directive: Directive = {
  7. mounted(el: HTMLElement, binding: DirectiveBinding) {
  8. if (typeof binding.value !== "function") {
  9. throw "callback must be a function";
  10. }
  11. // 定义变量
  12. let pressTimer: any = null;
  13. // 创建计时器( 2秒后执行函数 )
  14. const start = (e: any) => {
  15. if (e.button) {
  16. if (e.type === "click" && e.button !== 0) {
  17. return;
  18. }
  19. }
  20. if (pressTimer === null) {
  21. pressTimer = setTimeout(() => {
  22. handler(e);
  23. }, 1000);
  24. }
  25. };
  26. // 取消计时器
  27. const cancel = () => {
  28. if (pressTimer !== null) {
  29. clearTimeout(pressTimer);
  30. pressTimer = null;
  31. }
  32. };
  33. // 运行函数
  34. const handler = (e: MouseEvent | TouchEvent) => {
  35. binding.value(e);
  36. };
  37. // 添加事件监听器
  38. el.addEventListener("mousedown", start);
  39. el.addEventListener("touchstart", start);
  40. // 取消计时器
  41. el.addEventListener("click", cancel);
  42. el.addEventListener("mouseout", cancel);
  43. el.addEventListener("touchend", cancel);
  44. el.addEventListener("touchcancel", cancel);
  45. }
  46. };
  47. export default directive;