美文网首页
微信小程序非首页实现tabbar效果

微信小程序非首页实现tabbar效果

作者: 默_声 | 来源:发表于2019-04-18 17:33 被阅读0次

目前开发微信小程序,需求是要在非首页实现tabbar的切换效果,但是,官方文档的tabbar只能在首页使用,而且还有个坑,tabbar的第一个页面必须是app.json文件pages数组的第一个,不然显示不出来。
接下来说一下如何在非首页实现tabbar效果,这个效果在Android里面非常的简单,使用
fragment进行切换就可以实现,那么也是把这种思维带到了小程序中,使用component进行切换,先上代码。
page.js

Page({
  data: {
    currentTab: 0,
    items: [{
        "iconPath": "/icon/overview.png",
        "selectedIconPath": "/icon/overview_sel.png",
        "text": "首页"
      },
      {
        "iconPath": "/icon/overview.png",
        "selectedIconPath": "/icon/overview_sel.png",
        "text": "推荐"
      },
      {
        "iconPath": "/icon/overview.png",
        "selectedIconPath": "/icon/overview_sel.png",
        "text": "我的"
      }
    ]
  },
  /**
   * 选项卡点击事件
   */
  tabbarClick: function(e) {
    let that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }

  },
})

page.json

{
  "usingComponents": {
    "my-component": "/components/component-tag-name",
    "aa":"/aa/aa",
    "bb":"/bb/bb"
  }
}

page.wxml

<view class='root'>
  <view class='box-h'>
    <view wx:if="{{currentTab == 0}}">
      <my-component class='component' />
    </view>
    <view  wx:if="{{currentTab == 1}}">
      <aa class='component' />
    </view>
    <view  wx:if="{{currentTab == 2}}">
      <bb class='component' />
    </view>
  </view>
  <view class="box-tabbar">
    <view class="tab-tiem {{currentTab == idx ? 'active' : 'default' }}" wx:for="{{items}}" wx:key="prototype" wx:for-index="idx" wx:for-item="item" data-current="{{idx}}" bindtap="tabbarClick">
      <text class="tab-text" wx:for-index="idx" data-current="{{idx}}" src="{{currentTab == idx ? item.selectedIconPath : item.iconPath }}">{{item.text}}</text>
      <image class="iconPath" wx:for-index="idx" data-current="{{idx}}" src="{{currentTab == idx ? item.selectedIconPath : item.iconPath }}"></image>
    </view>
  </view>
</view>

page.wxss


.iconPath {
  width:54rpx;
  height: 54rpx;
}

.tab-tiem{
  width: 100%;
  padding-top: 7rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column-reverse;
  background: #e4e4e4;
}
.component{
  height: 100%;
}
.root{
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  overflow:hidden
}
.box-tabbar {
  height: 10%;
  width: 100%;
  display: flex;
  position: fixed;
  bottom: 0;
  justify-content: space-between;
}

框架结构图


image.png

注意事项:
1.page.wxml使用的是wx:if来控制Component的显示隐藏,如果使用hidden的话,Component中如果还是用了自定义component的话,自定义component会获取不到正确的宽高,出现控件无法正常显示。

2.如果再页面中使用到自定义Component,用wx:if来控制显示隐藏的时候,pageLifetimes中的show()函数不会被调用,所以逻辑代码尽量在lifetimes ready()中执行。

相关文章

网友评论

      本文标题:微信小程序非首页实现tabbar效果

      本文链接:https://www.haomeiwen.com/subject/xaqnwqtx.html