如何在vue中使用触摸事件

为何用到了touch事件

在项目中,用mint-ui做了一个下拉刷新的功能。在其他手机都可以,但是在iphonex上当下拉到虚拟键位置,下拉框就会卡住,不会回弹。所以为了不让用户下拉到虚拟键设置了下拉高度和回弹的最大距离,用到了touch事件。

touch事件

最基本的touch事件有四个:

  • touchstart

当在屏幕上按下手指时触发

  • touchmove

当在屏幕上移动手指时触发

  • touchend

当在屏幕上抬起手指时触发

  • touchcancel

当一些更高级别的事件发生的时候(如电话接入或者弹出信息)会取消当前的touch操作,即触发touchcancel。一般会在touchcancel时暂停游戏、存档等操作

它们的触发顺序是touchstart–>touchmove–>touchend

touch可以产生一个TouchEvent对象。

注意:在很多情况下,触摸事件和鼠标事件会同时被触发(目的是让没有对触摸设备优化的代码仍然可以在触摸设备上正常工作)。如果你使用了触摸事件,可以调用 event.preventDefault()来阻止鼠标事件被触发。(我认为可能上拉下的过程中触发了点击事件,所以下拉不回弹。)

如何在Vue中监听touch事件

	/**
	 * [TouchMove 监听touch事件]
	 */
	 TouchMove () {
	   this.$refs.idealist.addEventListener('touchmove', this.handleTouchMove, false)
	   this.$refs.idealist.addEventListener('touchstart', this.handleTouchStart, false)
	   this.$refs.idealist.addEventListener('touchend', this.handleTouchtouchend, false)
	 }

mounted中调用this.TouchMove().然后在methods里面写入你想要监听事件的方法。我这里应用到了touchmovetouchstart

	/**
     * [handleTouchStart 记录Touch开始的Y轴数值]
     */
    handleTouchStart (event) {
      this.startY = event.touches[0].clientY
    },
    /**
     * [handleTouchMove 监听touchmove时Y轴的数值]
     */
    handleTouchMove (event) {
      if (event.touches[0].clientY - this.startY > 300) {
        this.lodTopBool = true
        this.$refs.loadmoretwo.onTopLoaded()
        this.allLoaded = false
        this.page = 1
        this.pageSize = 20
        setTimeout(() => {
          this.lodTopBool = false
        }, 300)
        this.loadTopList()
      }
    }
  • clientX:触摸目标在视口中的x坐标。
  • clientY:触摸目标在视口中的y坐标。
  • identifier:标识触摸的唯一ID。
  • pageX:触摸目标在页面中的x坐标。
  • pageY:触摸目标在页面中的y坐标。
  • screenX:触摸目标在屏幕中的x坐标。
  • screenY:触摸目标在屏幕中的y坐标。
  • target:触目的DOM节点目标。
    这样就实现了在vue中监听touch事件,超过一定距离下拉刷新自动回弹刷新的功能。

猜你喜欢

转载自blog.csdn.net/oQingHeYiKan12/article/details/84228514