uni-app中构建tab选项卡

uni-app中构建tab选项卡

手机APP最常见的莫过于tab选项卡,其特点是可以无缝滚动,且不会出现滚动条。有点类似轮播,但是比轮播更灵活。

1.scroll-view

uni-app官方文档为我们提供了scroll-view。来实现横向或竖向的滚动

横向

<scroll-view scroll-x="true" class="h-tab" :scroll-left="scroll_left" scroll-with-animation="true">
.....
</scroll-view>
  • scroll-x:设置超出部分才不会出现滚动条
  • scroll-left:滚动时距离左边距离
  • scroll-with-animation:滚动动画
.h-tab {
		white-space: nowrap; //不换行
		width: 100%; //宽度适应屏幕
		height: 80upx;
		line-height: 80upx;
		position: fixed;
		top: 0;
		left: 0;
		background: #fff;
}

竖向

竖向有坑的地方
具体看下面,因为我是把竖向滚动放在swiper中的,这里就不重复说了

官方文档

2.swiper

<swiper style="flex:1;margin-top:80upx" duration="800" @change="changeSwiper" :current="swiperIndex">
				<swiper-item v-for="(elem,i) of swiperData" :key="i">
					<scroll-view scroll-y="true" style="height:100%" @scrolltolower="onToButtom">
						.....
					</scroll-view>
				</swiper-item>
</swiper>

swiper一定要设置高度,不然会显示默认高度150upx;
我们可以使用flex布局,外部大的容器设置为100vh,让swiper的样式flex:1,这样就会自动撑满屏幕。
接下来一定要设置scroll-view的高度,否则内部容器,无法滚动,只铺满swiper容器的高度。
只有设置成height:100%才会出现滚动。

  • duration:轮播切换过度时间
  • current:当前轮播索引
  • changeSwiper:切换轮播图触发的事件

这里还有点要注意,因为是竖向滑动,所以原生的下拉触底周期函数失效,需要使用scroll提供的API——scrolltolower

swiper文档

3.dom元素获取

关于获取元素的一些api

3.1 获取设置的dataset

 e.currentTarget.dataset.index

3.2 获取元素宽高

let view = uni.createSelectorQuery().select(".h-tab-item");
		view.boundingClientRect(data => {
		console.log(data.width)
}).exec();

更多请参考官网

dom元素获取

4. 整合逻辑

  • 通过dataset设置tab索引,通过动态绑定设置swiper索引:current:swiperIndex
  • 滑动tab,获取索引,使tab索引与swiper的索引相同
  • 滑动swiper,获取索引赋值给tabIndex,并获取一个tab的宽高,然后动态改变scroll-left
  • 修改tab的样式,根据tabIndex来显示active
   //tab点击事件
	changeTab(e) {
				this.tabIndex = e.currentTarget.dataset.index;//获取tab索引
				this.swiperIndex = this.tabIndex //实时更新swiper的索引与tab索引相同
			},
			//滚动到底部事件,因为是设置了scroll-view所以无法使用原生的onReachBottom生命周期函数
			onToButtom() {
				console.log('refresh');
				uni.showLoading({
					title: '加载中',
				});

				setTimeout(() => {
					this.setData();
					uni.hideLoading();
				}, 1000)
			},
	 //swiper滑动事件		
	 changeSwiper(e) {
				let index = e.target.current;
				this.tabIndex = index;
				let view = uni.createSelectorQuery().select(".h-tab-item");
				view.boundingClientRect(data => {
				this.scroll_left = data.width * index //根据下标移动tab
	 }).exec();
	},

完整demo请参考

github地址

猜你喜欢

转载自blog.csdn.net/weixin_44003190/article/details/90704291