touch.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { on } from '../utils/dom/event';
  2. function getDirection(x, y) {
  3. if (x > y) {
  4. return 'horizontal';
  5. }
  6. if (y > x) {
  7. return 'vertical';
  8. }
  9. return '';
  10. }
  11. export var TouchMixin = {
  12. data: function data() {
  13. return {
  14. direction: ''
  15. };
  16. },
  17. methods: {
  18. touchStart: function touchStart(event) {
  19. this.resetTouchStatus();
  20. this.startX = event.touches[0].clientX;
  21. this.startY = event.touches[0].clientY;
  22. },
  23. touchMove: function touchMove(event) {
  24. var touch = event.touches[0]; // safari back will set clientX to negative number
  25. this.deltaX = touch.clientX < 0 ? 0 : touch.clientX - this.startX;
  26. this.deltaY = touch.clientY - this.startY;
  27. this.offsetX = Math.abs(this.deltaX);
  28. this.offsetY = Math.abs(this.deltaY); // lock direction when distance is greater than a certain value
  29. var LOCK_DIRECTION_DISTANCE = 10;
  30. if (!this.direction || this.offsetX < LOCK_DIRECTION_DISTANCE && this.offsetY < LOCK_DIRECTION_DISTANCE) {
  31. this.direction = getDirection(this.offsetX, this.offsetY);
  32. }
  33. },
  34. resetTouchStatus: function resetTouchStatus() {
  35. this.direction = '';
  36. this.deltaX = 0;
  37. this.deltaY = 0;
  38. this.offsetX = 0;
  39. this.offsetY = 0;
  40. },
  41. // avoid Vue 2.6 event bubble issues by manually binding events
  42. // https://github.com/vant-ui/vant/issues/3015
  43. bindTouchEvent: function bindTouchEvent(el) {
  44. var onTouchStart = this.onTouchStart,
  45. onTouchMove = this.onTouchMove,
  46. onTouchEnd = this.onTouchEnd;
  47. on(el, 'touchstart', onTouchStart);
  48. on(el, 'touchmove', onTouchMove);
  49. if (onTouchEnd) {
  50. on(el, 'touchend', onTouchEnd);
  51. on(el, 'touchcancel', onTouchEnd);
  52. }
  53. }
  54. }
  55. };