//長按指令 export default { install(Vue, options = { time: 2000 }) { 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 afunction, 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(e); }, options.time) } } // 取消計時器 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("touchmove", cancel); el.addEventListener("touchcancel", cancel); } }) } }