index.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { ref } from 'vue';
  2. const MIN_DISTANCE = 10;
  3. type Direction = '' | 'vertical' | 'horizontal';
  4. function getDirection(x: number, y: number) {
  5. if (x > y && x > MIN_DISTANCE) {
  6. return 'horizontal';
  7. }
  8. if (y > x && y > MIN_DISTANCE) {
  9. return 'vertical';
  10. }
  11. return '';
  12. }
  13. export function useTouch() {
  14. const startX = ref(0);
  15. const startY = ref(0);
  16. const deltaX = ref(0);
  17. const deltaY = ref(0);
  18. const offsetX = ref(0);
  19. const offsetY = ref(0);
  20. const direction = ref<Direction>('');
  21. const isVertical = () => direction.value === 'vertical';
  22. const isHorizontal = () => direction.value === 'horizontal';
  23. const reset = () => {
  24. deltaX.value = 0;
  25. deltaY.value = 0;
  26. offsetX.value = 0;
  27. offsetY.value = 0;
  28. direction.value = '';
  29. };
  30. const start = ((event: TouchEvent) => {
  31. reset();
  32. startX.value = event.touches[0].clientX;
  33. startY.value = event.touches[0].clientY;
  34. }) as EventListener;
  35. const move = ((event: TouchEvent) => {
  36. const touch = event.touches[0];
  37. deltaX.value = touch.clientX - startX.value;
  38. deltaY.value = touch.clientY - startY.value;
  39. offsetX.value = Math.abs(deltaX.value);
  40. offsetY.value = Math.abs(deltaY.value);
  41. if (!direction.value) {
  42. direction.value = getDirection(offsetX.value, offsetY.value);
  43. }
  44. }) as EventListener;
  45. return {
  46. move,
  47. start,
  48. reset,
  49. startX,
  50. startY,
  51. deltaX,
  52. deltaY,
  53. offsetX,
  54. offsetY,
  55. direction,
  56. isVertical,
  57. isHorizontal
  58. };
  59. }