自定义 tabBar · 小程序
第1步 先在根目录下新建自定义tabBar文件夹(一定要放到根目录下)
第2步、在 app.json 中的 tabBar 项指定 custom 字段,设置为true,同时其余 tabBar 相关配置也补充完整。
所有 tab 页的 json 里需声明 usingComponents 项,也可以在 app.json 全局开启。
第三步、 修改custom-tab-bar/index.js的文件
Component(
{
data :{
currentIndex: 0,
color: "#666666",
selectedColor: "#3d90f7",
list : [{
pagePath: "/page/index/index",
text: "首页",
iconPath: "/image/home.png",
selectedIconPath: "/image/home_selected.png"
},{
pagePath: "/page/other/index",
text: "其他",
iconPath: "/image/my.png",
selectedIconPath: "/image/my_selected.png"
}
]
},
methods:{
switchTab(e) {
const url = e.currentTarget.dataset.url;
const index = e.currentTarget.dataset.index;
wx.switchTab({url: url })
this.setData({
currentIndex: index
})
},
}
}
)
custom-tab-bar/index.wxml的文件
<cover-view class="tab-bar">
<cover-view class="item" bindtap='switchTab' wx:for="{{list}}" wx:key="index" data-index="{{index}}" data-url="{{item.pagePath}}">
<cover-image class="icon" src="{{index===currentIndex?item.selectedIconPath : item.iconPath}}"></cover-image>
<cover-view class="{{index===currentIndex?'textselected':'textselected2'}}">{{item.text}}</cover-view>
</cover-view>
</cover-view>
ps:这里需要注意的是list中的pagePath一定要写绝对路径/pages开头
第四步、把官方给的使用方法放到tabbar跳转页的onShow方法里,selected根据list下标位置进行设置。
在首页和其他页的js文件添加如下代码:
onShow: function () {
// tabbar
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
currentIndex: 0 //和custom-tab-bar/index.js文件的currentIndex是同一个
})
}
(用wx.switchTab({url: url })跳转到 【其他页面】 ,相当于刷新custom-tab-bar/index页面,currentIndex数据不会被改变,所以需要在跳转的页面重新设置。 如果是 【自己跳转到自己的页面】 currentIndex数据会发生改变, 所以不加上面那代码,会发现需要点两次数据才会改变------第一次是跳转其他页面,第二次是跳转自己页面 )