12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <template>
- <view
- @touchstart="handleTouchStart"
- @touchmove="handleTouchMove"
- @touchend="handleTouchEnd"
- class="swipe-detector"
- >
- <slot></slot>
- </view>
- </template>
- <script>
- export default {
- name: 'SwipeDetector',
- data() {
- return {
- startX: 0,
- startY: 0,
- endX: 0,
- endY: 0,
- minSwipeDistance: 50 // 最小滑动距离(px)
- }
- },
- methods: {
- handleTouchStart(e) {
- this.startX = e.touches[0].clientX
- this.startY = e.touches[0].clientY
- },
- handleTouchMove(e) {
- this.endX = e.touches[0].clientX
- this.endY = e.touches[0].clientY
- },
- handleTouchEnd() {
- const diffX = this.endX - this.startX
- const diffY = this.endY - this.startY
-
- // 确保是水平滑动(垂直滑动距离小于水平滑动距离的一半)
- if (Math.abs(diffY) < Math.abs(diffX) / 2) {
- if (Math.abs(diffX) > this.minSwipeDistance) {
- if (diffX > 0) {
- this.$emit('swipeRight')
- } else {
- this.$emit('swipeLeft')
- }
- }
- }
- }
- }
- }
- </script>
- <style>
- .swipe-detector {
- width: 100%;
- height: 100%;
- }
- </style>
|