小程序:左右滑动切换tab选项及页面

2021/5/18 12:55:09

本文主要是介绍小程序:左右滑动切换tab选项及页面,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

发现问题

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

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

最终实现效果:
在这里插入图片描述

解决方案

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

直接上源码吧,,,,,,,,,,,,我饿了,,,,,

我是直接封装组件哟

组件template

<template>
	<!-- 屏幕左右滑动切换tabs功能组件 -->
	<view class="tk-screen-scroll" @touchstart.stop="handleTouchstart" @touchend.stop="handleTouchend">
		<slot></slot>
	</view>
</template>
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 {
						this.indexs--;
						if (this.indexs <= 0) this.indexs = 0;
					}
					// 返回索引值
					this.$emit('getScreenIndes', this.indexs);
				}
			}
		}
	}
</script>

使用组件

<tk-screen-scroll :lengths="tabList.length" @getScreenIndes="getScreenIndes">
		// 内容
</tk-screen-scroll>

methods中加入

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

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



这篇关于小程序:左右滑动切换tab选项及页面的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程