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;
标签:el,vue,longPress,指令,addEventListener,cancel,null,pressTimer
From: https://www.cnblogs.com/songkomei/p/17314788.html