vue长按事件指令(v-longPress)

import type { Directive, App } from 'vue';

const longPress: Directive = {
  beforeMount: function (el, binding, vnode, prevVnode) {
    if (typeof binding.value !== 'function') {
      throw 'callback must be a function';
    }
    if (el) {
      el.className = el.className + ' no_select';
    }

    // 定义变量
    let pressTimer: number | null = null;
    // 创建计时器( 1秒后执行函数 )
    let start = (e: Event) => {
      if (e.type === 'click') {
        return;
      }
      if (pressTimer === null) {
        pressTimer = window.setTimeout(() => {
          handler(e);
        }, 1000);
      }
    };
    // 取消计时器
    let cancel = () => {
      if (pressTimer !== null) {
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    };
    // 运行函数
    const handler = (e: any) => {
      binding.value(e);
    };
    // 添加事件监听器
    el.addEventListener('mousedown', start);
    el.addEventListener('touchstart', start);
    // 取消计时器
    el.addEventListener('click', cancel);
    el.addEventListener('mouseout', cancel);
    el.addEventListener('touchend', cancel);
    el.addEventListener('touchcancel', cancel);
    el.addEventListener('mouseup', cancel);
  },
};

export function setupLongPressDirective(app: App) {
  app.directive('longPress', longPress);
}

export default longPress;
posted @ 2023-04-13 14:43  SKa-M  阅读(790)  评论(0编辑  收藏  举报