SwipeDetector.vue 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <template>
  2. <view
  3. @touchstart="handleTouchStart"
  4. @touchmove="handleTouchMove"
  5. @touchend="handleTouchEnd"
  6. class="swipe-detector"
  7. >
  8. <slot></slot>
  9. </view>
  10. </template>
  11. <script>
  12. export default {
  13. name: 'SwipeDetector',
  14. data() {
  15. return {
  16. startX: 0,
  17. startY: 0,
  18. endX: 0,
  19. endY: 0,
  20. minSwipeDistance: 50 // 最小滑动距离(px)
  21. }
  22. },
  23. methods: {
  24. handleTouchStart(e) {
  25. this.startX = e.touches[0].clientX
  26. this.startY = e.touches[0].clientY
  27. },
  28. handleTouchMove(e) {
  29. this.endX = e.touches[0].clientX
  30. this.endY = e.touches[0].clientY
  31. },
  32. handleTouchEnd() {
  33. const diffX = this.endX - this.startX
  34. const diffY = this.endY - this.startY
  35. // 确保是水平滑动(垂直滑动距离小于水平滑动距离的一半)
  36. if (Math.abs(diffY) < Math.abs(diffX) / 2) {
  37. if (Math.abs(diffX) > this.minSwipeDistance) {
  38. if (diffX > 0) {
  39. this.$emit('swipeRight')
  40. } else {
  41. this.$emit('swipeLeft')
  42. }
  43. }
  44. }
  45. }
  46. }
  47. }
  48. </script>
  49. <style>
  50. .swipe-detector {
  51. width: 100%;
  52. height: 100%;
  53. }
  54. </style>