touch.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { defineMixin } from '../vue'
  2. const MIN_DISTANCE = 10
  3. function getDirection(x, y) {
  4. if (x > y && x > MIN_DISTANCE) {
  5. return 'horizontal'
  6. }
  7. if (y > x && y > MIN_DISTANCE) {
  8. return 'vertical'
  9. }
  10. return ''
  11. }
  12. export const touchMixin = defineMixin({
  13. methods: {
  14. getTouchPoint(e) {
  15. if (!e) {
  16. return {
  17. x: 0,
  18. y: 0
  19. }
  20. } if (e.touches && e.touches[0]) {
  21. return {
  22. x: e.touches[0].pageX,
  23. y: e.touches[0].pageY
  24. }
  25. } if (e.changedTouches && e.changedTouches[0]) {
  26. return {
  27. x: e.changedTouches[0].pageX,
  28. y: e.changedTouches[0].pageY
  29. }
  30. }
  31. return {
  32. x: e.clientX || 0,
  33. y: e.clientY || 0
  34. }
  35. },
  36. resetTouchStatus() {
  37. this.direction = ''
  38. this.deltaX = 0
  39. this.deltaY = 0
  40. this.offsetX = 0
  41. this.offsetY = 0
  42. },
  43. touchStart(event) {
  44. this.resetTouchStatus()
  45. const touch = this.getTouchPoint(event)
  46. this.startX = touch.x
  47. this.startY = touch.y
  48. },
  49. touchMove(event) {
  50. const touch = this.getTouchPoint(event)
  51. this.deltaX = touch.x - this.startX
  52. this.deltaY = touch.y - this.startY
  53. this.offsetX = Math.abs(this.deltaX)
  54. this.offsetY = Math.abs(this.deltaY)
  55. this.direction = this.direction || getDirection(this.offsetX, this.offsetY)
  56. }
  57. }
  58. })