uniapp实现页面左右滑动切换tab选项

1. 发现问题

最近做小程序,发现很多东西小程序似乎都是没有的。

比如说一个常见的功能:移动端页面左右滑动时,能切换对应的tabs选项。

2. 解决方案

  1. 首先来讲,会去查一下小程序以及uniapp(我使用的uniapp,因为需要多端支持)中是否有支持该需求的功能模块。当然,我既然跑到来写博客了,就能说明很多问题了。
  2. 既然没有,那就自己封装一个功能组件;

直接上源码

2.1 组件template
<template>
	<!-- 屏幕左右滑动切换tabs功能组件 -->
	<view class="tk-screen-scroll" @touchstart.stop="handleTouchstart" @touchend.stop="handleTouchend">
		<slot></slot>
	</view>
</template>
2.2 组件js
export default {
		props: {
			lengths: { // tabs 项数 也叫长度
				type: [String, Number],
				default: 0
			}
		},
		data() {
			return {
				startX: 0,
				startY: 0,
				indexs: 0
			}
		},
		methods: {
			// 获取鼠标、手指初始位置
			handleTouchstart(e) {
				this.startTime = Date.now();
				this.startX = e.changedTouches[0].clientX;
				this.startY = e.changedTouches[0].clientY;
			},
			// 计算鼠标、手指偏移方向
			handleTouchend(e) {
				const endTime = Date.now();
				const length = this.lengths - 1;
				const endX = e.changedTouches[0].clientX;
				const endY = e.changedTouches[0].clientY;
				const differ = Math.abs(endY - this.startY);
				const dirvalX = endX - this.startX;
				// 纵轴偏移量不得超过 30,否则默认页面进行滚动操作
				if (differ <= 30) {
					// 按下时长不得超过 2秒,X轴滑动距离必须大于 40
					if (endTime - this.startTime > 2000 || Math.abs(dirvalX) <= 40) {
						return
					};
					// 判断滑动方向
					if (dirvalX > 0) {
						this.indexs++;
						if (this.indexs >= length) this.indexs = length;
					} else if (dirvalX < 0){
						this.indexs--;
						if (this.indexs <= 0) this.indexs = 0;
					}
					// 返回索引值
					this.$emit('getScreenIndes', this.indexs);
				}
			}
		}
	}
</script>
2.3 使用组件
<tk-screen-scroll :lengths="tabList.length" @getScreenIndes="getScreenIndes">
		// 内容
</tk-screen-scroll>

methods中加入

// 获取索引值 
getScreenIndes(indexs) {
	this.tabsIndex = indexs;
},

问题:如果和scroll-view搭配,注意点击事件,可以根据dirvalX =0进行解决,很简单的。


3. 最终实现效果:

在这里插入图片描述

  • 9
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 17
    评论
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一年两个

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值