简单说一下原理
首先介绍三个针对触摸屏设备的事件,分别是:
- touchstart:当手指触摸屏幕时触发,即触摸开始的时候;
- touchend:当手指离开屏幕时触发,即触摸结束的时候;
- touchcancel:当触摸事件被取消时触发,例如手指移出了触摸区域或者系统强制取消了触摸事件。
那么长按事件原理的大致逻辑伪代码就如下;
touchstart:当手指触摸屏幕时触发,即触摸开始的时候
{
启动一个定时任务事件在 500 毫秒后执行
}
ouchend:当手指离开屏幕时触发,即触摸结束的时候
【并且】
touchcancel:当触摸事件被取消时触发,例如手指移出了触摸区域或者系统强制取消了触摸事件
{
如果前面的定时任务事件还没触发,那么清空该定时任务
}
你说有点抽象?那先自己看看代码运行两遍研究一下
代码直接用
直接上代码,马上使用:
<template>
<view
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
@touchcancel="handleTouchCancel">
<slot></slot> <!-- Allows content to be inserted -->
</view>
</template>
<script setup lang="ts">
import { ref, onUnmounted, inject,defineProps } from 'vue'
const props = defineProps({
onLongPress:{
type: Function,
required: true
}
})
const timer = ref<number | null>(null);
const handleTouchStart = () => {
// Clear existing timer if it exists
if (timer.value) clearTimeout(timer.value);
// Set a new timer
timer.value = setTimeout(() => {
console.log(props)
props.onLongPress();
}, 500); // Trigger after 500 ms
};
const clearTimer = () => {
// Clear the timer when touch ends or is cancelled
if (timer.value) {
clearTimeout(timer.value);
timer.value = null;
}
};
const handleTouchEnd = () => {
clearTimer();
};
const handleTouchCancel = () => {
clearTimer();
};
onUnmounted(() => {
// Ensure no timers are left running
clearTimer();
});
</script>
父组件使用调用示例:
<k-long-press-view :on-long-press="handleLongPress">
<view style="min-height: 50rpx;">
长按触发
</view>
</k-long-press-view>
<script setup lang="ts">
function handleLongPress() {
console.log('长按触发')
}
</script>