Handle long press events, click events, and default event conflicts in vue

written in front

Example is h5 project. Technology stack: vue + vant + nuxt.

Introduction to knowledge points:

touchstart: // Triggered when the finger is placed on the screen

touchend: // Triggered when the finger leaves the screen

touchmove: // Triggered by sliding the finger on the screen

touchcancel: // Triggered when the system cancels the touch event

Pages and requirements:

History search function:

  • Click a historical record and fill in the historical content in the search box;
  • Long press a history record: delete;

code:

html:

<div
  v-for="item in historyList"
  :key="item"
  class="disease-tag"
  @touchstart.prevent="delHistory($event,'deleteItem', item)"
  @touchend.prevent="touchend"
>
  {
   
   { item }}
</div>

data:

longTouch: false, // 判断是否是长按; 

Events triggered by touchstart:

// 模拟长按
clearTimeout(this.loop)// 再次清空定时器,防止重复注册定时器(会把点击事件也阻止掉)
this.longTouch = false // 关键
this.loop = setTimeout(() => {
  this.longTouch = true  // 关键
  this.showDialog = true
}, 600)

Events for leaving the touch screen:

touchend() {
  clearTimeout(this.loop) // 清空定时器,防止重复注册定时器
  if(!this.longTouch){
    //如果不是长按,执行点击事件
    this.change(this.curItem)
  }
},

Why write like this:

There are both click and long press events on the div.

Because vue does not have its own long-press event, we use touchstartand touchendsimulate long-press, but after long-press, it will trigger the default event, such as the menu appears, and the mobile terminal will appear to select copy;

But if you directly block the default event, the click event will also be blocked—whether it is directly blocked or blocked @touchstart.preventin the code ;event.preventDefault

So how can it be done - prevent the default event and trigger the click event correctly?

Use the feature that is triggered before the event, combined with a timer to solve it touchstart.click

Regarding this feature, we can simply print and see:

Bind these three events at the same time:

 <div 
   v-for="item in historyList"
   :key="item" @click="click"
   @touchstart="touchstart"
   @touchend="touchend"
 </div> 

Print the execution sequence:

Click on:

Press:

So you can use touchstart to simulate click events.

Guess you like

Origin blog.csdn.net/dongkeai/article/details/127405205