1、编写长按指令
// longPress.js
function dobind (el, binding){
if (typeof binding.value !== 'function') {
const compName = vNode.context.name
// pass warning to console
let warn = [longpress:] provided expression '${binding.expression}' is not a function, but has to be
if (compName) { warn += Found in component '${compName}' }
console.warn(warn)
}
let pressTimer = null
// 开始按下
let start = (e) => {
// 如果是点击事件,不启动计时器,直接返回
if (e.type === 'click' && e.button !== '0') {
return
}
if (pressTimer == null) {
// 创建定时器 (1s之后执行长按功能函数)
pressTimer = setTimeout(() => {
binding.value(e) // 执行长按功能函数
}, 1000)
}
}
// 取消按下
let cancel = (e) => {
if (pressTimer != null) {
clearTimeout(pressTimer)
pressTimer = null
}
}
// 添加事件监听器
el.addEventListener("mousedown", start)
el.addEventListener("touchstart", start)
// 取消计时器
el.addEventListener("click", cancel);
el.addEventListener("mouseout", cancel);
el.addEventListener("touchend", cancel);
el.addEventListener("touchcancel", cancel);
}
export default {
bind(el, binding) {
dobind(el, binding)
}
}
2.在组件中使用指令 directives: { LongPress }