class VueTouchEvent {
constructor(el, binding) {
this.domEL = el;
this.binding = binding;
this.touchType = this.binding.arg;
if (typeof this.binding.value !== 'function') throw new Error('v-touch 必须指定函数')
this.callback = this.binding.value;
this.init(this.touchType)
}
init(touchtype) {
switch (touchtype) {
case 'longtap':
this.bindLongTap()
break;
case 'swiper-up':
this.bindSwiperUp()
break;
case 'swiper-down':
this.bindSwiperDown()
break;
case 'swiper-left':
this.bindSwiperLeft()
break;
case 'swiper-right':
this.bindSwiperRight()
break
default:
}
}
bindLongTap() {
const dom = this.domEL;
dom.addEventListener('touchstart', () => {
this.pressTimer = null
this.pressTimer = setTimeout(() => {
clearTimeout(this.pressTimer)
this.callback(this.domEL)
}, 1000)
})
dom.addEventListener('touchend', () => {
clearTimeout(this.pressTimer)
this.pressTimer = null
})
}
bindSwiperUp() {
this.domEL.addEventListener('touchstart', (e) => {
this.clientY = Math.ceil(e.changedTouches[0].clientY)
})
this.domEL.addEventListener('touchend', (e) => {
if (this.clientY - e.changedTouches[0].clientY > 50) {
this.callback(this)
}
this.clientY = null;
})
}
bindSwiperDown() {
this.domEL.addEventListener('touchstart', (e) => {
this.clientY = Math.ceil(e.changedTouches[0].clientY)
})
this.domEL.addEventListener('touchend', (e) => {
if (this.clientY - e.changedTouches[0].clientY < -50) {
this.callback(this)
}
this.clientY = null;
})
}
bindSwiperLeft() {
this.domEL.addEventListener('touchstart', (e) => {
this.clientX = Math.ceil(e.changedTouches[0].clientX)
})
this.domEL.addEventListener('touchend', (e) => {
if (this.clientX - e.changedTouches[0].clientX > 50) {
this.callback(this)
}
this.clientX = null;
})
}
bindSwiperRight() {
this.domEL.addEventListener('touchstart', (e) => {
this.clientX = Math.ceil(e.changedTouches[0].clientX)
})
this.domEL.addEventListener('touchend', (e) => {
if (this.clientX - e.changedTouches[0].clientX < -50) {
this.callback(this)
}
this.clientX = null;
})
}
}
const touch = function(vue, opotions) {
vue.directive('touch', {
bind: function(el, binding) {
new VueTouchEvent(el, binding)
}
})
};
Vue.use(touch)
<div id="vm" v-cloak>
<div>
<img v-touch:longtap="callback" src="./images/logo.png" alt="" srcset="">
</div>
</div>