|
| 1 | +export default { |
| 2 | + props: { |
| 3 | + mdSwipeable: Boolean, |
| 4 | + mdSwipeThreshold: { |
| 5 | + type: Number, |
| 6 | + default: 150 |
| 7 | + }, |
| 8 | + mdSwipeRestraint: { |
| 9 | + type: Number, |
| 10 | + default: 100 |
| 11 | + }, |
| 12 | + mdSwipeTime: { |
| 13 | + type: Number, |
| 14 | + default: 300 |
| 15 | + } |
| 16 | + }, |
| 17 | + data: () => ({ |
| 18 | + swipeStart: false, |
| 19 | + swipeStartTime: null, |
| 20 | + swiped: null, |
| 21 | + touchPosition: { |
| 22 | + startX: 0, |
| 23 | + startY: 0 |
| 24 | + } |
| 25 | + }), |
| 26 | + computed: { |
| 27 | + getSwipeElement () { |
| 28 | + return this.mdSwipeElement || window |
| 29 | + } |
| 30 | + }, |
| 31 | + methods: { |
| 32 | + handleTouchStart (event) { |
| 33 | + this.touchPosition.startX = event.touches[0].screenX |
| 34 | + this.touchPosition.startY = event.touches[0].screenY |
| 35 | + this.swipeStartTime = new Date() |
| 36 | + |
| 37 | + this.swipeStart = true |
| 38 | + }, |
| 39 | + handleTouchMove (event) { |
| 40 | + if (!this.swipeStart) { |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + const touchmoveX = event.touches[0].screenX |
| 45 | + const touchmoveY = event.touches[0].screenY |
| 46 | + |
| 47 | + const actualX = touchmoveX - this.touchPosition.startX |
| 48 | + const actualY = touchmoveY - this.touchPosition.startY |
| 49 | + |
| 50 | + const elapsedTime = new Date() - this.swipeStartTime |
| 51 | + |
| 52 | + if (elapsedTime <= this.mdSwipeTime) { |
| 53 | + if (Math.abs(actualX) >= this.mdSwipeThreshold && Math.abs(actualY) <= this.mdSwipeRestraint) { |
| 54 | + this.swiped = actualX < 0 |
| 55 | + ? 'left' |
| 56 | + : 'right' |
| 57 | + } else if (Math.abs(actualY) >= this.mdSwipeThreshold && Math.abs(actualX) <= this.mdSwipeRestraint) { |
| 58 | + this.swiped = actualY < 0 |
| 59 | + ? 'up' |
| 60 | + : 'down' |
| 61 | + } |
| 62 | + } |
| 63 | + }, |
| 64 | + handleTouchEnd () { |
| 65 | + this.touchPosition = { |
| 66 | + startX: 0, |
| 67 | + startY: 0 |
| 68 | + } |
| 69 | + this.swiped = null |
| 70 | + this.swipeStart = false |
| 71 | + }, |
| 72 | + }, |
| 73 | + mounted () { |
| 74 | + if (this.mdSwipeable) { |
| 75 | + this.getSwipeElement.addEventListener('touchstart', this.handleTouchStart, false) |
| 76 | + this.getSwipeElement.addEventListener('touchend', this.handleTouchEnd, false) |
| 77 | + this.getSwipeElement.addEventListener('touchmove', this.handleTouchMove, false) |
| 78 | + } |
| 79 | + }, |
| 80 | + beforeDestroy () { |
| 81 | + if (this.mdSwipeable) { |
| 82 | + this.getSwipeElement.removeEventListener('touchstart', this.handleTouchStart, false) |
| 83 | + this.getSwipeElement.removeEventListener('touchend', this.handleTouchEnd, false) |
| 84 | + this.getSwipeElement.removeEventListener('touchmove', this.handleTouchMove, false) |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments