首先创建longpress.js文件
import Vue from 'vue'
Vue.directive('longpress', {
bind: function (el, binding, vNode) {
if (typeof binding.value !== 'function' && vNode.context !== undefined) {
let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be`;
console.warn(warn);
}
let pressTimer = null
// 开始倒计时执行
let start = (e) => {
if (e.type === 'click' && e.button !== 0) {
return;
}
if (pressTimer === null) {
pressTimer = setTimeout(() => {
handler()
}, 1000)
}
}
// 清除事件
let cancel = () => {
if (pressTimer !== null) {
clearTimeout(pressTimer);
pressTimer = null;
}
};
// 运行方法
const handler = (e) => {
binding.value(e);
};
el.addEventListener("mousedown", start);
el.addEventListener("touchstart", start);
el.addEventListener("click", cancel);
el.addEventListener("mouseup", cancel);
el.addEventListener("mouseout", cancel);
el.addEventListener("touchend", cancel);
el.addEventListener("touchcancel", cancel);
}
})
原理是mousedown和touchstart事件,1秒后执行对应的方法,如果按下时间不够1s,就会清除倒计时事件,对应的方法就不会被执行了
在main.js中引入
然后在页面中试试
如果执行的方法需要传参,则需要用到以下这种写法