微信小程序tab切换

wxml

<view class="nav-box">
  <!-- tab框 -->
  <view class="nav-tab">
    <view wx:for="{{navList}}" wx:key="index" data-current="{{index}}" class="item {{currTab == index? 'active':''}} " bindtap="tabSelect">
      <text>{{item}}</text> 
    </view>
  </view>
  <!-- tab框显示内容  可以使用wx:if判断也可以使用hidden判断,这个可以根据需求选择使用-->
  
  <view class="content"  hidden="{{currTab !== 0}}">内容1</view>
  <view class="content" hidden="{{currTab !== 1}}">内容2</view>
  <view class="content" wx:if="{{currTab == 2}}">内容3</view>
  <view class="content" wx:if="{{currTab == 3}}">内容4</view>
</view>

wxss

.nav-tab {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  background-color: #fff;
  margin-bottom: 10rpx;
  display: flex;
  justify-content: space-around;
}

.nav-tab .item {
  border-bottom: 6rpx solid transparent;
}

.nav-tab .item.active {
  border-bottom: 6rpx solid #f00;
}

.content {
  text-align: center;
  padding: 20rpx;
}

js

 data:{
    navList: ['分类1', '分类2', '分类3', '分类4'],
    currTab: 0, //导航栏当前项
  },

  //导航点击
  tabSelect: function (e) {
    console.log(e)
    let index = e.currentTarget.dataset.current
    if (this.data.currTab == index) {
      return false
    } else {
      this.setData({
        currTab: index
      })
    }
  },

扩展点:
wx:if vs hidden的区别
wx:if 是遇 true 显示,hidden 是遇 false 显示。
wx:if 在隐藏的时候不渲染,而 hidden 在隐藏时仍然渲染,只是不展现出来。
一般来说,wx:if 有更高的切换消耗而 hidden 有更高的初始渲染消耗。因此,如果需要频繁切换的情景下,用 hidden 更好,如果在运行时条件不大可能改变则 wx:if 较好。

发布了21 篇原创文章 · 获赞 1 · 访问量 7809

猜你喜欢

转载自blog.csdn.net/eva_feng/article/details/105090753