useTouch.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { ref } from 'vue'
  2. export function useTouch() {
  3. const direction = ref<string>('')
  4. const deltaX = ref<number>(0)
  5. const deltaY = ref<number>(0)
  6. const offsetX = ref<number>(0)
  7. const offsetY = ref<number>(0)
  8. const startX = ref<number>(0)
  9. const startY = ref<number>(0)
  10. function touchStart(event: any) {
  11. const touch = event.touches[0]
  12. direction.value = ''
  13. deltaX.value = 0
  14. deltaY.value = 0
  15. offsetX.value = 0
  16. offsetY.value = 0
  17. startX.value = touch.clientX
  18. startY.value = touch.clientY
  19. }
  20. function touchMove(event: any) {
  21. const touch = event.touches[0]
  22. deltaX.value = touch.clientX - startX.value
  23. deltaY.value = touch.clientY - startY.value
  24. offsetX.value = Math.abs(deltaX.value)
  25. offsetY.value = Math.abs(deltaY.value)
  26. direction.value = offsetX.value > offsetY.value ? 'horizontal' : offsetX.value < offsetY.value ? 'vertical' : ''
  27. }
  28. return {
  29. touchStart,
  30. touchMove,
  31. direction,
  32. deltaX,
  33. deltaY,
  34. offsetX,
  35. offsetY,
  36. startX,
  37. startY
  38. }
  39. }