2

Long press and touch events on Vue mobile

Blog description

The information involved in the article comes from the Internet and personal summary, which is intended to summarize personal learning and experience. If there is any infringement, please contact me to delete it, thank you!

instruction

The demand on the mobile phone will inevitably encounter gesture-related, such as div long press and click events. Long press may be operations such as sharing or deleting. The general form is displayed through a pop-up window.

accomplish

In fact, it mainly uses the touch events of dom, touchstart, touchmove, touchend

Code

<template>
  <div>
    <div class="btn-long" @touchstart="handlerTouchstart" @touchmove="handlerTouchmove" @touchend="handlerTouchend">长按我</div>
    <div v-if="clickShow">单击</div>
    <div v-if="longClickShow">双击</div>
  </div>
</template>

<script>

export default {
  name: 'LongTouch',
  data () {
    return {
      // 定时器
      loop: 0,
      clickShow: false,
      longClickShow: false
    }
  },
  methods: {
    handlerTouchstart () {
      this.loop = setTimeout(() => {
        this.loop = 0
        // 执行长按要执行的内容
        this.clickShow = false
        this.longClickShow = true
      }, 500) // 定时的时间
      return false
    },
    handlerTouchmove () {
      // 清除定时器
      clearTimeout(this.loop)
      this.loop = 0
    },
    handlerTouchend () {
      // 清除定时器
      clearTimeout(this.loop)
      if (this.loop !== 0) {
        // 单击操作
        this.clickShow = true
        this.longClickShow = false
      }
    }
  }
}
</script>

<style scoped>

.btn-long {
  width: 200px;
  height: 30px;
  background-color: red;
}
</style>

Demo

image-20210811175110960

It is found that the effect of selected text will appear when long-pressing, which affects the experience more.

Optimize the experience

Add styles to css so that the selected effect will not appear.

* {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

thanks

Universal network

And the hardworking self, personal blog , GitHub test , GitHub

Public Account-Guizimo, Mini Program-Xiaogui Blog


归子莫
1k 声望1.2k 粉丝

信息安全工程师,现职前端工程师的全栈开发,三年全栈经验。