微信小程序微信小程序开发小程序

微信小程序中自定义tabbar

2018-11-25  本文已影响13人  齐梓曦

微信小程序在app.json中进行全局配置其中关于tabbar的部分已然可以满足大部分的项目需求。然而对于一些需要一些别致的样式或者在不同页面表现得tabbar不一致的情况下却是不能满足需求的。

类似的文章,网上也存有不少。我本后来者在此留下个人的做法仅供参考。(此处图标采用iconfont图标,有关字体图标在小程序的使用参照《小程序中使用iconfont》)

1, 创建tabbar模板

有关template的用法请自行查看官方文档。
tabbar.wxml


  <template name="tabbar">
        <view class="footerBar">
            <block wx:for{{tabbarList}} wx:key{{item}}>
                <view class="fb_inner" bindtap="fbTapFn" data-item='{{item}}'>
                    <text class="iconfont {{item.icon}} fb_icon {{item.active?'active':''}} "></text>
                    <text class="fb_txt {{item.active?'active':''}}">{{item.txt}}</text>
                </view>
            </block>
        </view>
  </template>

对应的布局样式如下:
tabbar.wxss

      .footerBar{
        position: fixed;
        right: 0;
        bottom: 0;
        left: 0;
        height: 50px;
        background: #000;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .footerBar .fb_inner{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    .fb_inner .fb_icon{
        font-size: 16px;
        color: #cfcfcf;
    }
    .fb_inner .fb_txt{
        margin-top: 8px;
        font-size: 14px;
        color: #cfcfcf;
    }
    .fb_inner .active{
        color: green;
    }

2, tabbar上的点击事件

关于点击事件,有两种做法。
第一种,在引入界面如同写该页面的事件函数一般对应你tabbar模版上的方法名新建一个函数。
第二种,单独写一个tabbar相关的js,在引入tabbar模板的页面js中引入tabbar.js中的方法。

tabbar.js


  function fbTapFn (){
    console.log(e)
  }
  module.export{
    fbTapFn:fbTapFn  
  }

3,以pages/index页面为例如下:

3.1 index.wxml

  import '../template/tabbar'
  <!--
    // 点击事件第一种的话此处直接如此即可
    // <template is="tabbar" data="{{tabbarList}}"></template>
  -->
   <!--点击事件第二种-->
    <view bind:tap="bindTapChange"> // 使用容器盛放主要绑定事件触发内部事件
          <template is="tabbar" data="{{tabbarList}}"></template>
    </view>

3..2 index.js

  
  import {fbTapFn } from '../template/tabbar' // 第二种点击方案需引入
  Page({
    data:{
      tabbarList:[
        {icon:'字体图标',active:'是否激活',txt:'tabItem文本'},
        {icon:'字体图标',active:'是否激活',txt:'tabItem文本'},
        {icon:'字体图标',active:'是否激活',txt:'tabItem文本'}
      ]
      // 第一种点击方式
      // fbTapFn (e) { console.log(e) }
      // 第二种点击方式
      bindTapChange(e){
         fbTapFn (e)
      }
    }
  })

3.3 最后不要忘了将tabbar的样式引入

建议进行全局引入


至此,小程序中如何自定义tabbar基本告捷。此处只是提供一种思路。另自定义tabbar不能使用原生的tabbar的wx.switchTab进行跳转。故页面没有原声tabbar的平滑过渡。既然提到此处,我看过一种解决的思路,即原声tabbar与自定义tabbar同时存在,原生负责执行点击切换的动作,自定义负责展示效果。觉得是一种可行的方案,但本人未进行实现验证。

上一篇下一篇

猜你喜欢

热点阅读