在一个微信小程序中,需要实现一个功能,点击页面某一个按钮,显示不同底部导航栏,实现效果如下
- 代码仓库地址:
https://github.com/MrZHLF/tabBar
- 这个就需要自定义底部菜单栏,
app.json
文件的tabBar需要给custom
设置为true
建立导航栏公共组件
<cover-view class="tab-bar">
<cover-view class="tab-bar-border"></cover-view>
<cover-view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
<cover-image src="{{selected == index ? item.selectedIconPath : item.iconPath}}"></cover-image>
<cover-view style="color: {{selected == index ? selectedColor : color}}">{{item.text}}</cover-view>
</cover-view>
</cover-view>
对应js文件,其中list
对应的就是底部导航栏内容
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [
{
pagePath: "/pages/index/index",
text: "首页",
iconPath: "/images/home.png",
selectedIconPath: "/images/home_b.png"
},
{
pagePath: "/pages/indexcate/indexcate",
text: "发现",
iconPath: "/images/more2.png",
selectedIconPath: "/images/more2_b.png"
},
{
pagePath: "/pages/mycenter/mycenter",
text: "我的",
iconPath: "/images/my.png",
selectedIconPath: "/images/my_b.png"
}
]
},
methods: {
switchTab(e) {
let data = e.currentTarget.dataset
let url = data.path
wx.switchTab({
url
})
this.setData({
selected: data.index
})
}
}
})
- 注意:如需实现 tab 选中态,要在当前页面下,通过 getTabBar 接口获取组件实例,并调用 setData 更新选中态。可参考底部的代码示例。
- 自定义底部菜单栏需要在每个文件
onShow
添加对应js代码
onShow: function () {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
},
切换底部导航栏
- 其实做这个的时候,我在component组件有创建了一个单独对底部导航栏封装一个组件,
data: {
selected:0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [
{
pagePath: "/shoping/index/index",
text: "首页",
iconPath: "/static/images/tabbar/icon-1.png",
selectedIconPath: "/static/images/tabbar/icon-1-active.png"
},
{
pagePath: "/shoping/shop/caregory/index",
text: "分类",
iconPath: "/static/images/tabbar/icon-2.png",
selectedIconPath: "/static/images/tabbar/icon-2-active.png"
},
{
pagePath: "/shoping/member/cart/index",
text: "购物车",
iconPath: "/static/images/tabbar/icon-4.png",
selectedIconPath: "/static/images/tabbar/icon-4-active.png"
},
{
pagePath: "/shoping/member/index/index",
text: "会员中心",
iconPath: "/static/images/tabbar/icon-5.png",
selectedIconPath: "/static/images/tabbar/icon-5-active.png"
}
]
},
- 从每个组件接收一个当前选择的状态
properties: {
selected: {
type: Number,
default:0
}
},
如果不写这个的话,通过switchTab
跳转都会刷新页面,状态都是初始化为默认值了,其中这个selected
来判断是当前那个页面
- 对于这个组件,因为是从另外一个页面跳转另外一个底部,需要在每个导航页面引入这个组件
{
"usingComponents": {
"nav-tabar": "/components/shoping-tabbar/index"
}
}
- 页面使用,并在当前页面定义
selected
传递过去
<text>首页</text>
<nav-tabar selected="{{selected}}"></nav-tabar>
以上就是功能所需要的代码,已经上传github了,可以自行下载,在修改修改,优化优化代码,感觉这样写体验效果不是很好,如果有好的方案,可以留言哈