微信小程序自定义tabbar详解

  • Post author:
  • Post category:小程序


之前用的tabbar一直是系统自带的,后来发现制约太多,不是特别美观。于是还是自定义了一套tabbar使用。

首先新建一个templte文件夹,我放的位置是与pages同级的,路径就是”/template/template”

template.wxml

<template name="tabBar">
<view class="tabBar">
  <block wx:for="{{tabBar}}" wx:for-item="item" wx:key="tabBar">
    <view class="tabBar-item">
      <navigator open-type="redirect" url="{{item.pagePath}}">
        <view><image class="icon" src='{{item.iconPath}}'></image></view>
        <view class="{{item.current== 1 ? 'tabBartext' :''}}">
          <text class='text'>{{item.text}}</text>
        </view>
      </navigator>  
    </view>
  </block>
</view>
</template>

template.js

//初始化数据
function tabbarinit() {
  return [
    {
      "current": 0,
      "pagePath": "/pages/business/bueiness",
      "iconPath": "/image/rate.png",
      "selectedIconPath": "/image/on_rate.png",
      "text": "进度"
    },
    {
      "current": 0,
      "pagePath": "/pages/businessList/businessList",
      "iconPath": "/image/work.png",
      "selectedIconPath": "/image/on_work.png",
      "text": "工作"
    },
    {
      "current": 0,
      "pagePath": "/pages/my/my",
      "iconPath": "/image/my.png",
      "selectedIconPath": "/image/on_my.png",
      "text": "我的"
    }
  ]

}

function tabbarmain(bindName = "tabdata", id, target) {
  var that = target;
  var bindData = {};
  var otabbar = tabbarinit();
  otabbar[id]['iconPath'] = otabbar[id]['selectedIconPath']//换当前的icon
  otabbar[id]['current'] = 1;
  bindData[bindName] = otabbar
  that.setData({ bindData });
}


module.exports = {
  tabbar: tabbarmain
}

如此,这样就ok了,效果如下图:

在这里插入图片描述

看到有用户反馈东西不太齐全,感到抱歉,现在补充一下

接下来在要使用的页面进行配置,以index为例

index.html

<import src="../../template/template.wxml"/>
<template is="tabBar" data="{{tabBar:bindData.tabBar}}"/>

index.js

const app = getApp()
var template = require('../../template/template.js');
Page({
  data: {

  },
  onLoad: function () {
    template.tabbar("tabBar", 0, this)//0表示第一个tabbar  如果在其它页面,比如说是「我的」,那就更改0这个索引值
  },
})



版权声明:本文为m0_45041148原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。