來源https://github.com/OFED/translation/issues/3
Vue.directive('longpress', {
bind: function(el, binding, vNode) {
// 確保提供的表達式是函數
if (typeof binding.value !== 'function') {
// 獲取組件名稱
const compName = vNode.context.name
// 將警告傳遞給控制台
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
// 定義函數處理程序
// 創建計時器( 1秒后執行函數 )
let start = (e) => {
if (e.type === 'click' && e.button !== 0) {
return
}
if (pressTimer === null) {
pressTimer = setTimeout(() => {
// 執行函數
handler()
}, 1000)
}
}
// 取消計時器
let cancel = (e) => {
// 檢查計時器是否有值
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('mouseout', cancel)
el.addEventListener('touchend', cancel)
el.addEventListener('touchcancel', cancel)
}
})
