背景:一些业务场景须要对比方辨认二维码的长按事件进行上报、具体用处因业务而异
思路:个别二维码扫描机会在长按后600ms內触发,以600ms为绝对工夫进行计算
常见api:
@touchstart // 手指触摸手机屏幕时触发
@touchmove // 手指在手机屏幕挪动时触发
@touchend // 手指来到手机屏幕时触发
@touchcancel // 零碎勾销touch事件的时候触发,比方电话
@click // 点击时触发
执行程序
- touchstart > touchmove > touchend > click
- touchmove 与 click事件互斥,即touchmove触发执行,click事件不再执行
- touchend 和 touchcancel实践上不会同时触发
实现形式: - 在touchstart事件中获取以后工夫戳
在touchmove事件中做判断,
- 定义规定:在该办法内获取以后工夫戳 减去 在touchstart事件中取到的工夫戳
- 与600ms做大小判断
- 在touchmove事件中 通过在touchstart事件中定义的办法进行判断、如果小于600ms就 将touchstart事件中获取的工夫戳置为0
在touchend中判断
touchstart事件中获取的工夫戳 与 在touchmove事件中定义的规定 为true
- 此时上报你想要的货色
- 在 touchcancel上报
附代码:
<template><div> <!-- 长按辨认二维码 --> <img :src="url" @touchstart="touchstart()" @touchmove="touchmove()" @touchend="touchend()" @touchcancel="touchcancel()"></div></template><script> // data data () { return { startTime: 0, // 用户按下的时候工夫戳 endTime: 0, // 用户手抬起时的工夫戳 touchTime: 600, // 长按毫秒工夫 isMove: false } } // methods // 模仿h5长按事件. 相干参数默认已定义 touchstart () { this.startTime = new Date().getTime() }, touchmove () { if (this.isMove) return this.isMove = true if (!this.timeDiff()) { this.startTime = 0 } }, touchend () { if (this.startTime && this.timeDiff()) { this.recordLog('上报touchend') } this.isMove = false }, touchcancel () { this.recordLog('上报touchcancel') this.isMove = false }, timeDiff () { let timeDiff = new Date().getTime() - this.startTime let isSend = timeDiff >= this.touchTime return isSend }, recordLog (val) { console.log('这里是上报的信息', val) }</script>