import Vue from 'vue'
Vue.directive('longpress', function (el, binding){
// if (typeof binding.value !== 'function') {
// throw Error(binding.value + '不是函數')
// }
// Make sure expression provided is a function
if (typeof binding.value !== 'function') {
// Fetch name of component
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) {
// 創建定時器 (2s之后執行長按功能韓函數)
pressTimer = setTimeout(() => {
binding.value() // 執行長按功能函數
}, 2000)
}
}
// 取消按下
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);
})
1.在src目錄下 新建文件夾utils文件夾,然后新建derective.js,復制上方代碼,粘貼到derective.js;
2.在main.js中引入 該自定義指令js
3.在html中可以這樣使用即可
<div id="touchId" v-longpress="touchStar" :class="tipShow == true ? 'tips' : ''" :data-content="tip">長按觸發</div>
傳送門:測試demo完整代碼
