uni-app 手指滑动事件介绍+ 实现判断手指左右滑动组件的封装

一,手指滑动操作的原理

手指在屏幕上产生了移动:

  • 手指按下屏幕事件 touchstart;
  • 手指离开屏幕事件 touchend;
  • 手指在屏幕上的坐标 event.changedTouches[0].clientX 和 clientY

手指在屏幕上的时间不能太长

  • 记录下手指按下的时间 Date.now()
  • 记录下手指离开的时间 Date.now()
  • 在手指离开的时候做减法运算,求时间差

根据坐标判断滑动的位置

代码示例

1,定义两个触发事件

<view class="touch" 
@touchstart="touchStart"
@touchend="touchEnd"
></view>
export default {
	data(){
		return {
			// 刚触碰的时间
		  	startTime:0,
		  	// 刚触碰的位置
		  	startPosition:0,
		  	// 结束的位置
		  	endPosition:0	
		}
	},
	methods: {
		touchStart(event){
			// 获取初始时间
			this.startTime = Date.now()
			// 获取初始的位置
			this.startPosition = event.changedTouches[0].clientX
		},
		touchEnd(event){
			const endTime = Date.now()
			if (endTime - this.startTime > 2000){
				// 如果手指滑动的距离超过2s 就默认不合法
				return;
			}
			// 判断其滑动的距离是否值得触发,给定一个10 的距离
			if (Math.abs(this.endPosition - this.startPosition) > 10){
				this.endPosition = event.changedTouches[0].clientX
				var elePosition = this.endPosition - this.startPosition > 0 ? "right": "left"
			} else {
				return;
			}
			console.log(elePosition)
		},
	}
}

二,实现代码的封装–组件

  • 实现插槽slot 功能
  • 像外部(例如:父组件)传递滑动的方向

1,在pages 同级页面下新建 components 文件夹,新建 swiperPosition.vue 组件

<template>
	<view
	@touchstart="touchStart"
	@touchend="touchEnd"
	>
		<slot></slot>
	</view>
</template>
<script>
export default {
	data(){
		return {
		  	startTime:0,
		  	startPosition:0,
		  	endPosition:0	
		}
	},
	methods: {
		touchStart(event){
			this.startTime = Date.now()
			this.startPosition = event.changedTouches[0].clientX
		},
		touchEnd(event){
			const endTime = Date.now()
			if (endTime - this.startTime > 2000){
				return;
			}
			if (Math.abs(this.endPosition - this.startPosition) > 10){
				this.endPosition = event.changedTouches[0].clientX
				var elePosition = this.endPosition - this.startPosition > 0 ? "right": "left"
			} else {
				return;
			}
			// console.log(elePosition)
			// 在此处需要将数据传递过去,使用子组件给父组件传值的方式
			this.$emit('positionData', elePosition)
		},
	}
}
</script>

2,在需要改组件的页面中引入,并且监听属性的值

<swiper-postino @positionData="getPositionData">
	......
</swiper-postino>
import swiperPosition from '@/components/swiperPosition'
export default {
	components: {swiperPosition},
	methods: {
		getPositionData(e){
			// 获取传递过来的参数值
			console.log(e)
		}
	}
}
  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值