uni-app 左右滑动组件封装

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

  • 手指按下屏幕事件 touchstart;
  • 手指离开屏幕事件 touchend;
  • 手指在屏幕上的坐标 event.changedTouches[0].clientX 和 clientY
  • clientX:X轴方向(左右)
  • clientY:Y轴方向(上下)

根据坐标判断滑动的位置 

代码示例

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()
				// 如果手指滑动的时间超过3s 就默认不合法
				if (endTime - this.startTime > 3000) {
					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,在需要的组件页面中引入,并且监听属性的值

<template>
	<view>
		<swiperPosition @positionData="getPositionData">
			触摸滑动
		</swiperPosition>
	</view>
</template>

<script>
    //组件绝对路径
	import swiperPosition from '@/components/swiperPosition.vue'
	export default {
		data() {
			return {
			
			}
		},
		components: {
			swiperPosition
		},
		methods: {
			getPositionData(e) {
				// 获取传递过来的参数值
				console.log(e)
			}
		}
	}
</script>

<style scoped lang="scss">

</style>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值