当前位置: 首页 > news >正文

封装长按触发事件的uniapp组件

简单说一下原理

首先介绍三个针对触摸屏设备的事件,分别是:

  1. touchstart:当手指触摸屏幕时触发,即触摸开始的时候;
  2. touchend:当手指离开屏幕时触发,即触摸结束的时候;
  3. 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 existsif (timer.value) clearTimeout(timer.value);// Set a new timertimer.value = setTimeout(() => {console.log(props)props.onLongPress();}, 500); // Trigger after 500 ms
};const clearTimer = () => {// Clear the timer when touch ends or is cancelledif (timer.value) {clearTimeout(timer.value);timer.value = null;}
};const handleTouchEnd = () => {clearTimer();
};const handleTouchCancel = () => {clearTimer();
};onUnmounted(() => {// Ensure no timers are left runningclearTimer();
});
</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>
http://www.lryc.cn/news/344754.html

相关文章:

  • Docker 安装的MySQL迁移数据库
  • 算法训练Day28 | ● 122.买卖股票的最佳时机II ● 55. 跳跃游戏 ● 45.跳跃游戏II
  • Linux(openEuler、CentOS8)基于chrony企业内网NTP服务器搭建实验
  • 前端开发框架Vue
  • Vue2中引入ElementUI
  • 华中科技大学雷达站部署
  • 小程序引入 Vant Weapp 极简教程
  • labview技术交流-将时间字符串转换成时间格式
  • 算法提高之迷宫问题
  • 泛微E9开发 通过点击按钮来复制选择的明细行
  • sqlalchemy 分表实现方案
  • QML进阶(十五) QML各种标准元素的用法
  • 【工具使用】快速实现Makefile模板的方法
  • Linux-信号执行
  • 在线听歌播放器 梨花带雨网页音乐播放器 网页音乐在线听 源码
  • 免费生成证件照
  • 深入探索数据链路层:网络通信的基石
  • STM32使用L9110驱动电机自制小风扇
  • C语言——队列的实现
  • 15-LINUX--线程的创建与同步
  • 【退役之重学Java】如何解决消息持续积压等问题
  • Linux下的SPI通信
  • 【转载】数字化工厂规划蓝图报告
  • 《基于GNU-Radio和USRP的雷达通信系统的实现》文献阅读
  • Sealos急速部署生产用k8s集群
  • VTK数据的读写--Vtk学习记录1--《VTK图形图像开发进阶》
  • Vue3专栏项目 -- 一、第一个页面(下)
  • 一栈走天下:使用HBuilderX高效搭建Uni-App微信小程序开发环境
  • docker安装Debian:11 freeswitch1.10.5
  • c3 笔记6 认识css样式表