use-touch.ts 1.2 KB

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