首先效果如下,通过手动点击上方3个tab选项卡也可切换内容,直接滑动也可实现切换内容
image.png
我们要将上方的三个选项卡先写出来
<!--Tab布局-->
<view class='title'>
<view class="{{0 == currentIndex ? 'title-sel-selected' : 'title-sel'}}" bindtap='titleClick' data-idx='0'>
<text>关注</text>
<hr class="line-style" />
</view>
<view class="{{1 == currentIndex ? 'title-sel-selected' : 'title-sel'}}" bindtap='titleClick' data-idx='1'>
<text>推荐</text>
<hr class="line-style" />
</view>
<view class="{{2 == currentIndex ? 'title-sel-selected' : 'title-sel'}}" bindtap='titleClick' data-idx='2'>
<text>资讯</text>
<hr class="line-style" />
</view>
</view>
滑动切换tab需要用到swiper来实现,其中swiper和swiper-item则都需要设置长度为100%,然后父组件通过Js方法设置自适应长度,其中recommend是我引入的自定义子组件。
<!--滑动切换 tab-->
<view style="height:{{ch}}rpx;">
<swiper bindchange='swiperTab' current='{{currentIndex}}' class="swiper">
<swiper-item>
<scroll-view class="scroll" scroll-y wx:if="{{currentIndex == 0}}">
<text>你好</text>
</scroll-view>
</swiper-item>
<swiper-item>
<scroll-view class="scroll" scroll-y wx:if="{{currentIndex == 1}}">
<recommend/>
</scroll-view>
</swiper-item>
<swiper-item>
<scroll-view class="scroll" scroll-y wx:if="{{currentIndex == 2}}">
<view class="tip">第3个tab</view>
</scroll-view>
</swiper-item>
</swiper>
</view>
js方法
// pages/mine/mine.js
Page({
/**
* 页面的初始数据
*/
data: {
currentIndex: 1,
ch: 0,
},
onLoad: function (options) {
wx.getSystemInfo({
success: res => {
//转为rpx
let ch = (750 / res.screenWidth) * res.windowHeight - 80;
this.setData({
ch
})
},
})
},
//用户点击tab时调用
titleClick: function (e) {
let currentPageIndex =
this.setData({
//拿到当前索引并动态改变
currentIndex: e.currentTarget.dataset.idx
})
},
//用户滑动切换tab调用
swiperTab: function (e) {
if (e.detail.source == 'touch') {
this.setData({
currentIndex: e.detail.current
});
}
},
})
wxss样式
.title {
width: 100%;
height: 88rpx;
background: white;
display: flex;
align-items: center;
justify-content: space-around;
}
.title-sel {
color: #24272c;
font-size: 32rpx;
display: flex;
flex-direction: column;
align-items: center;
}
.title-sel .line-style{
background: #fff;
height: 6rpx;
width: 40rpx;
position: relative;
margin-top: 10rpx;
}
.title-sel-selected{
color: #006bff;
font-size: 32rpx;
display: flex;
flex-direction: column;
align-items: center;
}
.title-sel-selected .line-style{
background: #006bff;
height: 6rpx;
width: 90rpx;
position: relative;
margin-top: 10rpx;
}
.swiper,.scroll{
height: 100%;
}
网友评论