edu/app/src/hooks/useTouch.ts

73 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-09-09 10:42:41 +00:00
import { reactive } from 'vue'
/**
* @description
* @return { Function }
*/
2022-09-09 10:42:41 +00:00
export function useTouch() {
// 最小移动距离
2022-09-09 10:42:41 +00:00
const MIN_DISTANCE = 10
const touch = reactive({
direction: '',
deltaX: 0,
deltaY: 0,
offsetX: 0,
offsetY: 0
})
/**
* @description
* @return { string }
*/
const getDirection = (x: number, y: number) => {
if (x > y && x > MIN_DISTANCE) {
2022-09-09 10:42:41 +00:00
return 'horizontal'
}
if (y > x && y > MIN_DISTANCE) {
2022-09-09 10:42:41 +00:00
return 'vertical'
}
2022-09-09 10:42:41 +00:00
return ''
}
2022-09-09 10:42:41 +00:00
/**
* @description
*/
const resetTouchStatus = () => {
2022-09-09 10:42:41 +00:00
touch.direction = ''
touch.deltaX = 0
touch.deltaY = 0
touch.offsetX = 0
touch.offsetY = 0
}
2022-09-09 10:42:41 +00:00
/**
* @description
*/
const touchStart = (event: any) => {
2022-09-09 10:42:41 +00:00
resetTouchStatus()
const events = event.touches[0]
touch.startX = events.clientX
touch.startY = events.clientY
}
2022-09-09 10:42:41 +00:00
/**
* @description
*/
const touchMove = (event: any) => {
2022-09-09 10:42:41 +00:00
const events = event.touches[0]
touch.deltaX = events.clientX - touch.startX
touch.deltaY = events.clientY - touch.startY
touch.offsetX = Math.abs(touch.deltaX)
touch.offsetY = Math.abs(touch.deltaY)
touch.direction = touch.direction || getDirection(touch.offsetX, touch.offsetY)
}
2022-09-09 10:42:41 +00:00
return {
touch,
resetTouchStatus,
touchStart,
touchMove
}
}