Open ALiangLiang opened 5 years ago
+1
+1
If you want to make this work on mobile only, switch the listeners to touchstart and touchend. And if you also want the action to be executed ONLY on tap-and-hold (like native mobile contextual menus), then you can use the snippet below.
exports.install = function (Vue, options) {
if (!options) options = {}
if (!options.duration) options.duration = 2000
Vue.directive('long-press', {
bind: function (el, binding) {
const self = this
this._timeout = null
this._hasMoved = false
this._ontouchend = function (e) {
self._hasMoved = false
clearTimeout(self._timeout)
}
this._ontouchmove = function () {
if (!self._hasMoved) {
self._hasMoved = true
}
}
this._ontouchstart = function (e) {
const context = this
self._timeout = setTimeout(function () {
if (!self._hasMoved) {
binding.value.call(context, e)
self._hasMoved = false
}
}, options.duration)
}
el.addEventListener('touchstart', this._ontouchstart, false)
el.addEventListener('touchmove', this._ontouchmove, false)
document.addEventListener('touchend', this._ontouchend, false)
},
unbind: function (el) {
clearTimeout(this._timeout)
el.removeEventListener('touchstart', this._ontouchstart)
el.removeEventListener('touchmove', this._ontouchmove)
document.removeEventListener('touchend', this._ontouchend)
}
})
}
In case anyone stumbles upon this, I forked this package with dev-gian's changes to add support for both touch and mouse.
https://github.com/JCharante/vue-long-press-directive
Thank you to kapetan and dev-gian
@JCharante looks good
In mobile device, only work touch event.