我是将选项卡单独抽取出来做一个自定义组件,组件内用slot插槽来改变内容 ,slot要设置成scroller-view才可以实现tabs固定而下方滑动。切换选项卡,只需要每次判断点击id,就可以切换内容。
//cpn-tabs.wxml
<view class="cpn-tab">
<view class="tab-control">
<view class="tab-group {{item.isActive?'active':''}}"
wx:for="{{titles}}"
wx:key="id"
bind:tap="handleTap"
data-index="{{index}}"
>
<text>{{item.value}}</text>
</view>
</view>
<view class="tab-content">
<scroll-view class="scroll-view" scroll-y>//这里要用到scroll-view来实现tabs悬浮,tabs以下滑动
<slot></slot>
</scroll-view>
</view>
</view>
//组件的wxss代码
page{
height: 100vh;
}
.cpn-tab{
height: 100vh;
}
.tab-control{
display: flex;
height: 90rpx;
}
.tab-group{
flex: 1;
padding: 10rpx;
text-align: center;
justify-content: center;
align-items: center;
}
.active{
color: #e4b04b;
}
.active text{
padding: 10rpx;
border-bottom: #e4b04b solid 6rpx;
}
.scroll-view{
height: calc( 100vh - 90rpx );//这一步很关键,设置tabs以下高度
}
//组件的js页面
Component({
data: {
isActive:false
},
properties: {
titles:{
type:Array,
value:[]
}
},
methods: {
handleTap(e){
const index=e.currentTarget.dataset.index;
this.setData({
currentIndex:index
});
this.triggerEvent("tabsItemChange",{index});//将每次监听到的点击事件传给引用页面
}
}
})
这是引用选项卡组件的wxml页面以及js页面
//js
data: {
titles:[
{
id:0,
value:"a",
isActive:true
},
{
id:1,
value:"b",
isActive:false
},
{
id:2,
value:"c",
isActive:false
}
]
},
handleTabsItemChange(e){
const {index}=e.detail;//拿到每次点击事件的index,对isActive进行设置
let {titles}=this.data;
titles.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false);
this.setData({
titles
})
},