根据id来实现小程序tab切换,

根据id来实现小程序tab切换,

本例根据绑定id来实现tab切换,但本例仍有缺陷,用for循环数据,无法实现切换。如有大神能够有更好方法,欢迎留言更正

WXML:

<view class="tab"> 
  <view bindtap="tabs" class="{{tabArr.curHdIndex=='0'? 'active' : ''}}" >tab-hd01</view> 
  <view bindtap="tabs" class="{{tabArr.curHdIndex=='1'? 'active' : ''}}" >tab-hd02</view> 
  <view bindtap="tabs" class="{{tabArr.curHdIndex=='2'? 'active' : ''}}" >tab-hd03</view> 
  <view bindtap="tabs" class="{{tabArr.curHdIndex=='3'? 'active' : ''}}" >tab-hd04</view> 
</view> 
 
<view class="tabcon"> 
  <view class="{{tabArr.curBdIndex=='0'? 'active' : ''}}">tab-bd01111</view> 
  <view class="{{tabArr.curBdIndex=='1'? 'active' : ''}}">tab-bd02222</view> 
  <view class="{{tabArr.curBdIndex=='2'? 'active' : ''}}">tab-bd03333</view> 
  <view class="{{tabArr.curBdIndex=='3'? 'active' : ''}}">tab-bd04444</view> 
</view>

WXSS:

.tab{
  display: flex;
  flex-direction:row; 
  height: 50px;
  line-height: 50px;

}
.tab view{
   25%;
  text-align: center;
}
.tab .active{
  display: inline-block;
  color: #188eee;
  border-bottom: 1px #188eee solid;
}
.tabcon view{
  display: none;
}
.tabcon .active{
  display: inline-block;
}

JS

Page({
  data: {
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0,
    }
  },
  tabs: function (e) {
    var dataId = e.currentTarget.id;
    var obj = {};
    obj.curHdIndex = dataId;
    obj.curBdIndex = dataId;
    
    this.setData({
      tabArr: obj
    }); 
  }
});