微信小程序实现左右滑动进行切换数据页面(touchmove)
?场景
手指触摸左右滑动进行切换数据
需要实现的是有一个tab栏,点选某一个tab的时候切换页面,手势滑动,左滑右滑效果和点击tab一样切换页面数据。

?事件的属性方法
这里我们要先了解几个微信的事件属性
- touchstart : 手指触摸动作开始
- touchmove:手指触摸后移动
- touchcancel:手指触摸动作被打断,如来电提醒,弹窗
- touchend: 手指触摸动作结束
- tap: 手指触摸后马上离开
- longpress: 手指触摸后,超过350ms再离开,如果指定了事件回调函数并触发了这个事件,tap事件将不被触发
- transitionend: 会在 WXSS transition 或 wx.createAnimation 动画结束后触发
- animationstart:会在一个 WXSS animation 动画开始时触发
- animationend: 会在一个 WXSS animation 动画完成时触发
从以上属性分析 我们需要完成 左右滑动的功能需要用到:
 @touchmove、@touchstart、@touchend
?实战左右滑动
HTML
亿点小知识:当手指从屏幕上离开的时候触发 "capture" 用于事件捕获
<view
	@touchmove.capture="handleTouchmove"
	@touchstart.capture="handleTouchstart"
	@touchend.capture="handleTouchend"
	style="height:100vh"
>
</view>
js
 先从手指开始 @touchstart 默认属性 event 中获取滑动的 pageX和pageY值
handleTouchstart(event) {
			this.flag = 0;
			this.lastX = event.changedTouches[0].pageX;
			this.lastY = event.changedTouches[0].pageY;
},
然后在判断 touchmove:手指触摸后移动中的距离
这里的 Math abs(x)方法返回指定值的绝对值。
返回值: Number x 的绝对值。如果 x 不是数字返回 NaN,如果 x 为 null 返回 0。
如果x = -2 那么返回值就是 2
handleTouchmove(event) {
			if (this.flag !== 0) {
				return;
			}
			let currentX = event.changedTouches[0].pageX;
			let currentY = event.changedTouches[0].pageY;
			let tx = currentX - this.lastX;
			let ty = currentY - this.lastY;
			//左右方向偏移大于上下偏移认为是左右滑动
			if (Math.abs(tx) - Math.abs(ty) > 5) {
				// 向左滑动
				if (tx < 0) {
					// 如果到最右侧
					console.log('向左滑动');
					this.flag = 1;
				// 向右滑动()
				} else if (tx > 0) {
					// 如果到最左侧
					this.flag = 2;
					console.log('向右滑动');
				}
			}
			//上下方向滑动
			else {
				if (ty < 0) {
					//向上滑动
					this.flag = 3;
				} else if (ty > 0) {
					//向下滑动
					this.flag = 4;
				}
			}
			//将当前坐标进行保存以进行下一次计算
			this.lastX = currentX;
			this.lastY = currentY;
	},
最后结束动作touchend
handleTouchend() {
			//停止滑动
			this.flag = 0;
		},
这里的this.flag 是用来记录是否需要重新滑动 不然会导致滑动过程中会一直触发touchmove
?

 以上就是微信小程序实现左右滑动进行切换数据页面感谢大家的阅读
 如碰到其他的问题 可以私下我 一起探讨学习
 如果对你有所帮助还请 点赞 收藏谢谢~!
 关注收藏博客 作者会持续更新…