<template>
    <div class='gesture-container' @touchstart="onTouchStart" @touchend="onTouchEnd" @touchmove="onTouchMove" @touchcancel="onTouchCancel">
        <slot name="body"></slot>
    </div>
</template>
<script>
const threshold = 8;

export default {
  data() {
    return {
      x: 0,
      lastX: 0,
      y: 0,
      lastY: 0
    };
  },

  props: {
    // fix ios 手机里上下滑动，出现水平x发生较大变化问题
    onlyVertical: {
      type: Boolean,
      default: false
    }
  },

  methods: {
    updateXY(evt) {
      let touch = evt.touches[0] || evt.changedTouches[0];

      this.lastX = this.x;
      this.lastY = this.y;

      this.x = touch.screenX;
      this.y = touch.screenY;
    },
    onXYUpdated() {
      let dx = this.x - this.lastX;
      let dy = this.y - this.lastY;
     

      if (Math.abs(dy) >= Math.abs(dx) || this.onlyVertical) {
        // 上下滑动
        if (Math.max(Math.abs(dx), Math.abs(dy)) < threshold) {
          return;
        }
        if (dy > 0) {
          this.$emit('down');
          console.log('down');
        } else {
          this.$emit('up');
          console.log('up');
        }
      } else {
        // 左右滚动
        if (Math.max(Math.abs(dx), Math.abs(dy)) < threshold) {
          return;
        }

        if (dx > 0) {
          this.$emit('right');
          console.log('right');
        } else {
          this.$emit('left');
          console.log('left  ');
        }
      }
    },
    onTouchStart(evt) {
      this.updateXY(evt);
    },
    onTouchMove(evt) {},
    onTouchEnd(evt) {
      this.updateXY(evt);
      this.onXYUpdated();
    },
    onTouchCancel(evt) {
      this.updateXY(evt);
      this.onXYUpdated();
    }
  }
};
</script>
<style lang="less" scoped>
.gesture-container {
}
</style>